有没有一种简单的方法来合并C#匿名对象
问题描述:
比方说,我有两个匿名对象是这样的:
Let's say I have two anonymous objects like this:
var objA = new { test = "test", blah = "blah" };
var objB = new { foo = "foo", bar = "bar" };
我想将它们组合得到:
I want to combine them to get:
new { test = "test", blah = "blah", foo = "foo", bar = "bar" };
我不知道是什么特性都是objA和objB在编译时。
我想这是像jQuery的扩展方法。
I won't know what the properties are for both objA and objB at compile time. I want this to be like jquery's extend method.
有人知道图书馆或.NET Framework类,可以帮助我做到这一点的?
Anybody know of a library or a .net framework class that can help me do this?
答
如果你真的做意味着在C#4.0的动态感,那么你可以这样做:
If you truly do mean dynamic in the C# 4.0 sense, then you can do something like:
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;
}
您甚至可以编写使用反射版本它有两个对象(非动态),并返回一个动态的。
You could even write a version using reflection which takes two objects (not dynamic) and returns a dynamic.