我想在运行时将属性动态添加到ExpandoObject中。例如,要添加一个调用NewProp的字符串属性,我想编写如下代码
var x = new ExpandoObject();
x.AddProperty("NewProp", System.String);这很容易实现吗?
发布于 2011-02-09 05:05:36
dynamic x = new ExpandoObject();
x.NewProp = string.Empty;或者:
var x = new ExpandoObject() as IDictionary<string, Object>;
x.Add("NewProp", string.Empty);发布于 2015-10-16 03:37:31
正如Filip - http://www.filipekberg.se/2011/10/02/adding-properties-and-methods-to-an-expandoobject-dynamicly/所解释的那样
你也可以在运行时添加一个方法。
x.Add("Shout", new Action(() => { Console.WriteLine("Hellooo!!!"); }));
x.Shout();发布于 2017-01-23 23:28:04
下面是一个示例助手类,它转换一个对象并返回一个Expando,其中包含给定对象的所有公共属性。
public static class dynamicHelper
{
public static ExpandoObject convertToExpando(object obj)
{
//Get Properties Using Reflections
BindingFlags flags = BindingFlags.Public | BindingFlags.Instance;
PropertyInfo[] properties = obj.GetType().GetProperties(flags);
//Add Them to a new Expando
ExpandoObject expando = new ExpandoObject();
foreach (PropertyInfo property in properties)
{
AddProperty(expando, property.Name, property.GetValue(obj));
}
return expando;
}
public static void AddProperty(ExpandoObject expando, string propertyName, object propertyValue)
{
//Take use of the IDictionary implementation
var expandoDict = expando as IDictionary<String, object>;
if (expandoDict.ContainsKey(propertyName))
expandoDict[propertyName] = propertyValue;
else
expandoDict.Add(propertyName, propertyValue);
}
}用法:
//Create Dynamic Object
dynamic expandoObj= dynamicHelper.convertToExpando(myObject);
//Add Custom Properties
dynamicHelper.AddProperty(expandoObj, "dynamicKey", "Some Value");https://stackoverflow.com/questions/4938397
复制相似问题