例如
var hello = new { Hello = "Hello" };
var world = new { World = "World" };
var helloWorld = hello + world;
Console.WriteLine(helloWorld.ToString());
//outputs {Hello = Hello, World = World}
有什么办法可以使这项工作?
No. hello and world objects are objects of different classes.
The only way to merge these classes is to use dynamic type generation (Emit). Here is example of such concatenation: http://www.developmentalmadness.com/archive/2008/02/12/extend-anonymous-types-using.aspx
Quote from mentioned article:
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.
否 - 它们是不同的类型,并且这+
两种类型的运算符都是未定义的。
作为旁注:我不认为你的意思是concatenate
. 在 C# 中,连接是您对两个或多个IEnumeration
s 执行的操作,使它们“端到端”。例如,Linq 方法Concat()
或String.Concat()
(字符串是 char 的“集合”)。您在问题中描述的更像是两种不相关类型之间的连接或多重继承。除了在下面的替代方案中使用自治类型之外,我想不出任何与 C# 中类似的东西:
var hello = new { Hello = "Hello" };
var world = new { World = "World" };
var helloWorld = new { hello, world };
Console.WriteLine(helloWorld.ToString());
//outputs { hello = { Hello = Hello }, world = { World = World } }
var helloWorld = new { Hello = hello.Hello, World = world.World };
您可以编写一个使用反射 API 自动执行此操作的方法。这与我认为的尽可能接近。
var hello = new { Hello = "Hello" };
var world = new { World = "World" };
var z = new { x = hello, y = world };
将其传递给 json 序列化程序和中提琴。