2009-09-21 120 views
1

如果我有两个对象,foobar,使用对象初始化语法delared ...合并含性能两个对象到一个对象

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

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

是否有可能将这些组合成一个单一的对象,这将看像这样...

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

我不知道你在问什么? – 2009-09-21 14:31:36

+0

我猜你希望能够做到这一点给予任何两个任意对象,而不是仅仅做foo = new {one = foo.one,three = bar.three} – ICR 2009-09-21 14:32:36

+0

(我的投票结果是重复的错误 - 我没有正确阅读这个问题。) – 2009-09-21 14:33:51

回答

7

不,你不能这样做。在编译时你有两种不同的类型,但在执行时你需要第三种类型来包含属性的联合。

我的意思是,你可以创建一个新的组件与相关新型的......但那么你就无法从反正你的代码中引用“正常”。

1

假设没有命名冲突,其可能使用反射来读取对象的属性,并将其合并到一个单一的类型,但你不能直接在您的代码访问此类型,而不在其上进行反思以及。

在4.0中,通过导入dynamic关键字,可以更容易地引用代码中的动态类型。它并不能使它成为更好的解决方案。

3

正如其他人所说,这不是方便做你的描述,但如果你只想做对综合性能进行一些处理:

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; 
}