Dynamically adding properties to a dynamic object?

后端 未结 3 703
半阙折子戏
半阙折子戏 2021-01-04 12:16

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

相关标签:
3条回答
  • 2021-01-04 13:08
    dynamic d = new ExpandoObject();
    ((IDictionary<string,object>)d)["test"] = 1;
    //now you have d.test = 1
    
    0 讨论(0)
  • 2021-01-04 13:11

    Here is a cleaner way

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

    0 讨论(0)
  • 2021-01-04 13:20

    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;
            }
    
    0 讨论(0)
提交回复
热议问题