我想在運行時動態地將屬性添加到ExpandoObject。所以例如添加一個字符串屬性調用NewProp我想寫一些類似於動態添加屬性到ExpandoObject
var x = new ExpandoObject();
x.AddProperty("NewProp", System.String);
這很容易嗎?
我想在運行時動態地將屬性添加到ExpandoObject。所以例如添加一個字符串屬性調用NewProp我想寫一些類似於動態添加屬性到ExpandoObject
var x = new ExpandoObject();
x.AddProperty("NewProp", System.String);
這很容易嗎?
dynamic x = new ExpandoObject();
x.NewProp = string.Empty;
或者:
var x = new ExpandoObject() as IDictionary<string, Object>;
x.Add("NewProp", string.Empty);
我從未意識到Expando *實現了* IDictionary
這是驚人的,我已經證明他們實際上成爲對象的示例代碼的屬性在我的帖子http://stackoverflow.com/questions/11888144/name-variable-using-string-net/ 11893463#11893463,謝謝 – 2012-08-10 02:42:16
正如菲利普這裏解釋 - 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();
這裏是一個樣本助手類,它轉換一個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);
}
}
用法:
//Create Dynamic Object
dynamic expandoObj= dynamicHelper.convertToExpando(myObject);
//Add Custom Properties
dynamicHelper.AddProperty(expandoObj, "dynamicKey", "Some Value");
的
可能重複[如何設置一個C#4動態對象的屬性,當你在另一個變量的名稱爲(http://stackoverflow.com/questions/ 3033410/how-to-set-a-property-of-ac-sharp-4-dynamic-object-when-you-have-the-name-in-an) – nawfal 2014-07-19 15:55:37