我想在运行时动态地向ExpandoObject添加属性。 例如,要添加一个名为NewProp的字符串属性,我想要编写类似于以下内容的代码:
var x = new ExpandoObject();
x.AddProperty("NewProp", System.String);
这可容易实现吗?
我想在运行时动态地向ExpandoObject添加属性。 例如,要添加一个名为NewProp的字符串属性,我想要编写类似于以下内容的代码:
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);
IDictionary<string, object>
,而不是 IDictionary<string, string>
。 - Stephen ClearyIDictionary
时,不要使用 dynamic
作为变量类型。 - user3791372IDictionary<string, object> myExpando = new ExpandoObject();
- Abel Wenning如Filip在此处所解释的 - http://www.filipekberg.se/2011/10/02/adding-properties-and-methods-to-an-expandoobject-dynamicly/
您也可以在运行时添加一个方法。
var x = new ExpandoObject() as IDictionary<string, Object>;
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<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");
这是我找到的最佳解决方案。但要小心使用,因为它可能无法适用于所有情况。请使用异常处理。
public static dynamic ToDynamic(this object obj)
{
return JsonConvert.DeserializeObject<dynamic>(JsonConvert.SerializeObject(obj));
}
//你可能想使用的另一个不错的扩展方法
public static T JsonClone<T>(this T source)
{
if (!typeof(T).IsSerializable)
{
throw new ArgumentException("The type must be serializable.", nameof(source));
}
var serialized = JsonConvert.SerializeObject(source);
return JsonConvert.DeserializeObject<T>(serialized);
}
这是我找到的最佳解决方案。但要小心使用。请使用异常处理,因为它可能无法适用于所有情况。
public static dynamic ToDynamic(this object obj)
{
return JsonConvert.DeserializeObject<dynamic>(JsonConvert.SerializeObject(obj));
}