一些字典, "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
:
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
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.