使用类型描述符
如评论中所述,Luke Foust 解决方案不适用于匿名类型。转换为 Dictionary 不起作用,我建议使用TypeDescriptor.GetProperties方法构建字典:
public static dynamic CombineDynamics(object object1, object object2)
{
IDictionary<string, object> dictionary1 = GetKeyValueMap(object1);
IDictionary<string, object> dictionary2 = GetKeyValueMap(object2);
var result = new ExpandoObject();
var d = result as IDictionary<string, object>;
foreach (var pair in dictionary1.Concat(dictionary2))
{
d[pair.Key] = pair.Value;
}
return result;
}
private static IDictionary<string, object> GetKeyValueMap(object values)
{
if (values == null)
{
return new Dictionary<string, object>();
}
var map = values as IDictionary<string, object>;
if (map == null)
{
return map;
}
map = new Dictionary<string, object>();
foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(values))
{
map.Add(descriptor.Name, descriptor.GetValue(values));
}
return map;
}
它现在使用匿名类型:
var a = new {foo = "foo"};
var b = new {bar = "bar"};
var c = CombineDynamics(a, b);
string foobar = c.foo + c.bar;
笔记:
我的 GetKeyValueMap 方法基于RouteValueDictionary类 (System.Web.Routing)。我重写了它(使用ILSpy反汇编它),因为我认为一个System.Web
类与对象合并无关。