Ich möchte dynamische Eigenschaften und dynamisch zu Objekten hinzufügen. Während eine ähnliche Frage beantwortet ist, dass verwendet ExpandoObject
:Dynamische Eigenschaften dynamisch zur Laufzeit hinzufügen
Dynamically Add C# Properties at Runtime
Während die obige Antwort Eigenschaften dynamisch hinzufügt, ist es nicht mein Bedürfnis zu erfüllen. Ich möchte Variableneigenschaften hinzufügen können.
Was ich reaaly wollen, ist eine generische Methode zu schreiben, die ein Objekt vom Typ nimmt T
und gibt ein ausgedehntes Objekt mit allen Feldern des Objekts plus einige mehr:
public static ExpandoObject Extend<T>(this T obj)
{
ExpandoObject eo = new ExpandoObject();
PropertyInfo[] pinfo = typeof(T).GetProperties();
foreach(PropertyInfo p in pinfo)
{
//now in here I want to get the fields and properties of the obj
//and add it to the return value
//p.Name would be the eo.property name
//and its value would be p.GetValue(obj);
}
eo.SomeExtension = SomeValue;
return eo;
}
Großen answe Danke. –