Add property to ExpandoObject with the same name as a string

前端 未结 2 1885
萌比男神i
萌比男神i 2021-02-01 15:55

Is there a way to add a property to an ExpandoObject with the same name as a string value?

For example, if I have:

string propName = \"ProductNumber\";
d         


        
相关标签:
2条回答
  • 2021-02-01 16:21

    Cast the ExpandoObject to an IDictionary<string,object> to do this:

    string propName = "ProductNumber";
    dynamic obj = new System.Dynamic.ExpandoObject();
    var dict = (IDictionary<string,object>)obj;
    dict[propName] = 123;
    
    0 讨论(0)
  • 2021-02-01 16:39

    ExpandoObject implements IDictionary<string, object>:

    ((IDictionary<string, object>)obj)[propName] = propValue
    

    I don't know off the top of my head whether you can use the indexer syntax with a dynamic reference (i.e., without the cast), but you can certainly try it and find out.

    0 讨论(0)
提交回复
热议问题