简体   繁体   English

有没有办法连接C#匿名类型?

[英]Is there a way to concat C# anonymous types?

For example 例如

var hello = new { Hello = "Hello" };
var world = new { World = "World" };
var helloWorld = hello + world;
Console.WriteLine(helloWorld.ToString());
//outputs {Hello = Hello, World = World}

Is there any way to make this work? 有没有办法让这项工作?

No. hello and world objects are objects of different classes. 不,你好,世界对象是不同类的对象。

The only way to merge these classes is to use dynamic type generation ( Emit ). 合并这些类的唯一方法是使用动态类型生成( Emit )。 Here is example of such concatenation: http://www.developmentalmadness.com/archive/2008/02/12/extend-anonymous-types-using.aspx 以下是此类连接的示例: 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. 该过程的工作方式如下:首先使用System.ComponentModel.GetProperties从匿名类型获取PropertyDescriptorCollection。 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. 启动Reflection.Emit创建一个新的动态程序集并使用TypeBuilder创建一个新类型,它是所涉及的所有属性的组合。 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. 然后缓存新类型以便重用,这样您就不必每次需要时都可以构建新类型。

No - They are different types and the + operator on both those types is undefined. 否 - 它们是不同的类型,这两种类型的+运算符是未定义的。

As a side note: I don't think you mean concatenate . 作为旁注:我不认为你的意思是concatenate In C#, concatenate is something you do to two or more IEnumeration s that puts them "end to end". 在C#中,连接是你对两个或多个IEnumeration所做的事情,它们将它们“端对端”。 For instance, the Linq method Concat() or String.Concat() (strings are "collections" of char). 例如,Linq方法Concat()String.Concat() (字符串是char的“集合”)。 What you describe in your question is more like a join or multiple-inheritance between two unrelated types. 您在问题中描述的内容更像是两个不相关类型之间的连接或多重继承。 I can't think of anything similar to that in C#, besides using autonomous types as in the alternative below: 除了在下面的替代方案中使用自治类型之外,我无法想到与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 };

You can write a method that does this automatically using reflection API. 您可以编写一个使用反射API自动执行此操作的方法。 That's as close to this as I see possible. 正如我所看到的那样,这与此接近。

var hello = new { Hello = "Hello" };
var world = new { World = "World" };
var z = new { x = hello, y = world };

pass it right to the json serializer and viola. 将它传递给json序列化器和中提琴。

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

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