Add property to ExpandoObject with the same name as a string

一个人想着一个人 提交于 2019-12-20 10:01:50

问题


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";
dynamic obj = new System.Dynamic.ExpandoObject();

I can create the property ProductNumber like:

obj.ProductNumber = 123;

But, can I create the property obj.ProductNumber based on the string propName? So, if I don't know what the name of the property will be in advanced, I can create it based on this input. If this is not possible with ExpandoObject, any other areas of C# I should look into?


回答1:


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.




回答2:


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;


来源:https://stackoverflow.com/questions/10048470/add-property-to-expandoobject-with-the-same-name-as-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!