简体   繁体   English

将两个包含属性的对象合并为一个对象

[英]Merging two objects containing properties into one object

If I have two objects, foo and bar , delared using object initializer syntax... 如果我有两个对象foobar ,则使用对象初始值设定项语法...

object foo = new { one = "1", two = "2" };

object bar = new { three = "3", four = "4" };

Is it possible to combine these into a single object, which would look like this... 是否可以将它们组合成单个对象,看起来像这样...

object foo = new { one = "1", two = "2", three = "3", four = "4" };

No, you can't do this. 不,你不能这样做。 You've got two separate types at compile-time, but you'd need a third type at execution time, to contain the union of properties. 在编译时,您有两个单独的类型,但是在执行时,您需要第三个类型来包含属性的并集。

I mean, you could create a new assembly with the relevant new type in... but then you wouldn't be able to reference it "normally" from your code anyway. 我的意思是,您可以在...中创建具有相关新类型的新程序集,但是无论如何您将无法从代码中“正常”引用它。

As others have said, it's not convenient to do what you describe but if you just want to do some processing on the combined properties: 正如其他人所说,按照您的描述进行操作并不方便,但是如果您只想对组合属性进行一些处理:

Dictionary<string, object> GetCombinedProperties(object o1, object o2) {
    var combinedProperties = new Dictionary<string, object>();
    foreach (var propertyInfo in o1.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))
        combinedProperties.Add(propertyInfo.Name, propertyInfo.GetValue(o1, null));
    foreach (var propertyInfo in o2.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))
        combinedProperties.Add(propertyInfo.Name, propertyInfo.GetValue(o2, null));
    return combinedProperties;
}

Assuming there are no naming conflicts, its possible using reflection to read the properties of the objects and merge it into a single type, but you'd not be able to access this type directly in your code without performing reflection on it as well. 假设没有命名冲突,可以使用反射来读取对象的属性并将其合并为单个类型,但是如果不对它进行反射,就无法直接在代码中访问该类型。

In 4.0, with the intruduction of the dynamic keyword, it would be possible to reference the dynamic type in code considerably easier. 在4.0中,通过引入dynamic关键字,可以很容易地在代码中引用动态类型。 It doesn't make it a better solution, mind. 请注意,这并不能使其成为更好的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM