Answers:
dynamic x = new ExpandoObject();
x.NewProp = string.Empty;
或者:
var x = new ExpandoObject() as IDictionary<string, Object>;
x.Add("NewProp", string.Empty);
Error 53 Cannot convert type 'System.Dynamic.ExpandoObject' to 'System.Collections.Generic.IDictionary<string,string>' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion
IDictionary<string, object>
,不是IDictionary<string, string>
。
IDictionary
,请勿将其dynamic
用作变量类型。
正如Filip在这里所解释的- //www.filipekberg.se/2011/10/02/adding-properties-and-methods-to-an-expandoobject-dynamicly/
您也可以在运行时添加方法。
x.Add("Shout", new Action(() => { Console.WriteLine("Hellooo!!!"); }));
x.Shout();
这是一个示例帮助器类,该类可转换对象并返回具有给定对象的所有公共属性的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");
我认为这可以按需要的类型添加新属性,而无需设置原始值,例如在类定义中定义属性时
var x = new ExpandoObject();
x.NewProp = default(string)