11

我有这个

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

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

所以,调用绑定器等有一个复杂的概念。这首先很难得到。有更简单的方法吗?

4

3 回答 3

26
dynamic d = new ExpandoObject();
((IDictionary<string,object>)d)["test"] = 1;
//now you have d.test = 1
于 2011-12-03T16:08:12.263 回答
7

这是一种更清洁的方法

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

于 2013-12-13T15:22:20.093 回答
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;
        }
于 2011-12-03T17:24:40.320 回答