Dynamically adding properties to a dynamic object?

此生再无相见时 提交于 2019-11-30 03:00:34

问题


i have this

dynamic d = new ExpandoObject();
d.Name = attribute.QualifiedName.Name;

so , i know that d will have a property Name. Now if i don't know the name of the property at compile time , how do i add that property to the dynamic. i found this SO Question

so, there is this complicated concept of call binders etc..which is tough to get in the first place.any simpler way of doing this ?


回答1:


dynamic d = new ExpandoObject();
((IDictionary<string,object>)d)["test"] = 1;
//now you have d.test = 1



回答2:


Here is a cleaner way

var myObject = new ExpandoObject() as IDictionary<string, Object>; myObject.Add("Country", "Ireland");




回答3:


You can also do like this:-

Dictionary<string,object> coll = new Dictionary<string,object>();
    coll.Add("Prop1","hello");
    coll.Add("Prop2",1);
    System.Dynamic.ExpandoObject obj = dic.Expando();

//You can have this ext method to better help

public static ExpandoObject Expando(this IEnumerable<KeyValuePair<string, object>> 
dictionary)
        {
            var expando = new ExpandoObject();
            var expandoDic = (IDictionary<string, object>)expando;
            foreach (var item in dictionary)
            {
                expandoDic.Add(item);
            }
            return expando;
        }


来源:https://stackoverflow.com/questions/8368885/dynamically-adding-properties-to-a-dynamic-object

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