动态添加属性到动态对象?

时间:2011-12-03 15:59:33

标签: c# c#-4.0 dynamic expandoobject

我有这个

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

所以,我知道d将拥有一个属性Name。现在,如果我在编译时不知道属性的名称,我该如何将该属性添加到动态。 我发现了这个SO Question

所以,有一个复杂的调用绑定器等概念......首先很难得到它。这样做的更简单的方法是什么?

3 个答案:

答案 0 :(得分:24)

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

答案 1 :(得分:5)

这是一种更清洁的方式

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

答案 2 :(得分:4)

您也可以这样做: -

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;
        }