简体   繁体   English

C#动态构建匿名对象

[英]C# Build anonymous object dynamically

In C# I can easily create an anonymous object like this at the compile time: 在C#中,我可以在编译时轻松创建这样的匿名对象:

var items = new {
 Price = 2000,
 Description = "",
 Locations = new List<string> { "", "" }  
};

My question is, it's possible to create this object at the runtime ? 我的问题是,可以在运行时创建这个对象吗? I've heard of emit/meta programming , but I don't know if it helps here. 我听说过emit / meta编程 ,但我不知道它是否有帮助。

Noting that these objects will be created inside a for loop (100 items or more), so I recommend techniques that allow type caching. 注意这些对象将在for循环内创建(100个项目或更多),因此我建议允许类型缓存的技术。

Thanks. 谢谢。

Update - Why I need this 更新 - 为什么我需要这个

  • One example could be implementing the Include functionality like in db.Users.Include("Users") , so I need to add the Users property at runtime on demand. 一个示例可能是在db.Users.Include("Users")实现Include功能,因此我需要在运行时按需添加Users属性。

Anonymous types are generated on compile time, and are just regular types. 匿名类型是在编译时生成的,只是常规类型。

Since you are talking beyond the compilation process, you don't have the 'generate an (anonymous) type on compile time' option any more, unless you compile the type yourself to an assembly you load right after generating it. 由于您在编译过程之外进行讨论,因此您不再需要“在编译时生成(匿名)类型”选项,除非您自己将类型编译为生成后立即加载的程序集。 System.Reflection.Emit is your friend here. System.Reflection.Emit是你的朋友。 This is quite expensive though. 这是非常昂贵的。

Personally I would skip all that hassle, and look into a type that is dynamic by nature, like ExpandoObject . 就个人而言,我会跳过所有麻烦,并研究一种本质上是动态的类型,比如ExpandoObject You can add properties, just like you would add entries to a dictionary: 您可以添加属性,就像将条目添加到字典中一样:

dynamic eo = new System.Dynamic.ExpandoObject();
IDictionary<string, object> d = (IDictionary<string, object>)eo;
d["a"] = "b";

string a = eo.a;

Result: 结果:

在此输入图像描述

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

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