假设我有两个这样的匿名对象:
var objA = new { test = "test", blah = "blah" };
var objB = new { foo = "foo", bar = "bar" };
我想将它们结合起来得到:
new { test = "test", blah = "blah", foo = "foo", bar = "bar" };
我不知道在编译时objA和objB的属性是什么。 我希望这就像jquery的extend方法。
有人知道可以帮我这样做的库或.net框架类吗?
答案 0 :(得分:26)
如果你真的在C#4.0意义上表示动态,那么你可以做类似的事情:
static dynamic Combine(dynamic item1, dynamic item2)
{
var dictionary1 = (IDictionary<string, object>)item1;
var dictionary2 = (IDictionary<string, object>)item2;
var result = new ExpandoObject();
var d = result as IDictionary<string, object>; //work with the Expando as a Dictionary
foreach (var pair in dictionary1.Concat(dictionary2))
{
d[pair.Key] = pair.Value;
}
return result;
}
您甚至可以使用反射来编写一个版本,该版本采用两个对象(非动态)并返回动态。
答案 1 :(得分:5)
正如评论中所述,Luke Foust solution不适用于匿名类型。 对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
类与对象合并无关。