向动态对象动态添加属性
本文关键字:动态 属性 添加 对象 | 更新日期: 2023-09-27 18:16:29
我有这个
dynamic d = new ExpandoObject();
d.Name = attribute.QualifiedName.Name;
所以,我知道d将有一个属性名。现在,如果我在编译时不知道属性的名称,我如何将该属性添加到动态。i found this SO Question
所以,有一个调用绑定等复杂的概念,一开始很难理解。有更简单的方法吗?
dynamic d = new ExpandoObject();
((IDictionary<string,object>)d)["test"] = 1;
//now you have d.test = 1
这是一个更干净的方法
var myObject = new ExpandoObject() as IDictionary<string, Object>;
myObject.Add("Country", "Ireland");
你也可以这样做:-
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;
}