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

标签 c# types anonymous

例如

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/

相关文章:

generics - 符合 Swift 协议(protocol)的泛型类型

c# - 无法在 GridView 上设置单元格颜色

javascript - 重定向到另一个页面时如何在链接或 li 上设置/保留 'active' 类?

c# - 在 C# 中的存储过程中使用全局临时表

c++ - 访问匿名命名空间内的变量 (c++)

java - 在匿名类中引用公共(public)枚举结果

c# - 发送匿名邮件 C#

c# - 当里面没有 DbSet<> 时如何使用 DbContext 进行查询?

java - 在 MATLAB 中读取文件时指定数据类型

pointers - 过滤 Vec<String> 时无法移出借用的内容