أود إضافة خصائص بشكل حيوي إلى 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);
كما هو موضح هنا من قبل فيليب - 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();
فيما يلي نموذج لفئة المساعد الذي يحول كائن ويعيد 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");