开发者

Is it possible to use ExpandoObject to create run-time properties?

开发者 https://www.devze.com 2023-02-16 18:21 出处:网络
Normally, we can create properties like this, dynamic expando = new ExpandoObject(); expando.Price = 45k;

Normally, we can create properties like this,

dynamic expando = new ExpandoObject();
expando.Price = 45k;
expando.Value = "Good";

In my case, I won't know the properties such as "Price" or "Value" until runtime. How, can I create such dynamic properties. Something like,

dynamic expando = new ExpandoObject();
expando[properties[0]] = 45k;
expando开发者_Python百科[properties[1]] = "Good";
expando[properties[2]] = "Red";
expando[properties[3]] = 8;

Anyway to achieve this kind of behavior.


Just use the fact that it implements IDictionary<string, Object>:

IDictionary<string, Object> expando = new ExpandoObject();
expando[properties[0]] = 45;
expando[properties[1]] = "Good";
expando[properties[2]] = "Red";
expando[properties[3]] = 8;

dynamic d = expando;
// Now use the properties as normal

On the other hand, if you don't know the properties until execution time, what's actually going to consume them? It may still make sense to use ExpandoObject - but equally it may make sense to use Dictionary<string, object> to start with.

0

精彩评论

暂无评论...
验证码 换一张
取 消