[英]Combine two objects into one
I'm preparing to pass values to a method: 我正在准备将值传递给方法:
private string BuildMessage(int templateID, string body, object data)
where the data param is an array of name/value pairs. 其中数据参数是名称/值对的数组。 To prepare my values for that data param I need to combine the properties of a strongly typed class with the values of a simple 2d array. 要为该数据参数准备值,我需要将强类型类的属性与简单2d数组的值结合起来。
What's the best way to merge those values? 合并这些值的最佳方法是什么?
You can easily get the properties and teir values via Reflection, like this: 您可以通过Reflection轻松获得属性和teir值,如下所示:
public Dictionary<string, string> GetParameters(object data)
{
if (data == null)
return null;
Dictionary<string, string> parameters = new Dictionary<string, string>();
foreach (PropertyInfo property in data.GetType().GetProperties())
parameters.Add(property.Name, property.GetValue(data, null).ToString());
return parameters;
}
Merging the two dictionaries shouldn't need further explanation :) 合并这两个字典不需要进一步说明:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.