简体   繁体   English

在 C# 中从字典创建匿名类型的对象

[英]Create a object of anonymous type from a dictionary in c#

一些字典, "key1" = "Value1, "key2" = "Value2", ... . 我需要创建一个对象

{ key1 : "Value1", key2 : "Value2", ... }

You cannot make an object of anonymous type at runtime.您不能在运行时创建匿名类型的对象。 Although anonymous types are, well, anonymous, they are static types, ie their members are known at compile time.尽管匿名类型是匿名的,但它们是静态类型,即它们的成员在编译时是已知的。 Unless all keys and values of your dictionary are known at compile time (which defeats the purpose, really) you cannot make a static type from the dictionary.除非你的字典的所有键和值在编译时都是已知的(这实际上违背了目的)你不能从字典中创建一个静态类型。

The next closest thing would be to use a dynamic type with an ExpandoObject :下一个最接近的事情是使用带有ExpandoObjectdynamic类型:

dynamic obj = new ExpandoObject();
var tmp = (IDictionary<string,object>)obj;
foreach (var p in dict) {
    tmp[p.Key] = p.Value;
}

Now you can write现在你可以写

Console.WriteLine("{0} {1}", obj.key1, obj.key2);

This will compile and run, as long as dict cntains keys key1 and key2 .这将编译并运行,只要dict cn包含键key1key2

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

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