Cra*_*aig 215 c# dynamic expandoobject c#-4.0
我想在运行时动态地向ExpandoObject添加属性.所以例如添加一个字符串属性调用NewProp我想写类似的东西
var x = new ExpandoObject();
x.AddProperty("NewProp", System.String);
Run Code Online (Sandbox Code Playgroud)
这很容易吗?
Ste*_*ary 460
dynamic x = new ExpandoObject();
x.NewProp = string.Empty;
Run Code Online (Sandbox Code Playgroud)
或者:
var x = new ExpandoObject() as IDictionary<string, Object>;
x.Add("NewProp", string.Empty);
Run Code Online (Sandbox Code Playgroud)
Him*_*tel 24
如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();
Run Code Online (Sandbox Code Playgroud)
小智 12
这是一个示例帮助器类,它转换Object并返回具有给定对象的所有公共属性的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;
if (expandoDict.ContainsKey(propertyName))
expandoDict[propertyName] = propertyValue;
else
expandoDict.Add(propertyName, propertyValue);
}
}
Run Code Online (Sandbox Code Playgroud)
用法:
//Create Dynamic Object
dynamic expandoObj= dynamicHelper.convertToExpando(myObject);
//Add Custom Properties
dynamicHelper.AddProperty(expandoObj, "dynamicKey", "Some Value");
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
98646 次 |
最近记录: |