开发者

How to create a dynamic property in this scenario [duplicate]

开发者 https://www.devze.com 2023-03-13 11:01 出处:网络
This question already has answers here: Adding unknown (at design time) properties to an ExpandoObject
This question already has answers here: Adding unknown (at design time) properties to an ExpandoObject (5 answers) Closed 8 years ago. 开发者_开发百科

I have a list which contains dynamic data. i.e

list[0].id=0;
list[1].id=1;
list[2].id=2;

I want to create a class which will have dynamic property names i.e

for(int i=0;i<list.count;i++)
{
    //create dynamic class with dynamic property name
    new {id+i=list[i].id} //this statement throws compilation error. 
}

what is alternative to this method?


You can't do what you are after with Anonymous classes as they build at compile time and not runtime. You need to use the ExpandoObject class

dynamic expando = new ExpandoObject();
var p = expando as IDictionary<String, object>;

for(int i=0;i<list.count;i++)
{
     p[id+i] = list[i].id;
}

//do something with the expando object

This is based on the post that Jani linked in his comment.

0

精彩评论

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