例如
var hello = new { Hello = "Hello" };
var world = new { World = "World" };
var helloWorld = hello + world;
Console.WriteLine(helloWorld.ToString());
//outputs {Hello = Hello, World = World}
有什么方法可以让它工作吗?
最佳答案
没有。你好和世界对象是不同类的对象。
合并这些类的唯一方法是使用动态类型生成 (Emit)。以下是此类连接的示例:http://www.developmentalmadness.com/archive/2008/02/12/extend-anonymous-types-using.aspx
引用文章中的内容:
The process works like this: First use System.ComponentModel.GetProperties to get a PropertyDescriptorCollection from the anonymous type. Fire up Reflection.Emit to create a new dynamic assembly and use TypeBuilder to create a new type which is a composite of all the properties involved. Then cache the new type for reuse so you don't have to take the hit of building the new type every time you need it.
关于c# - 有没有办法连接 C# 匿名类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2726913/