2016-12-07 2 views
1

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; 
} 

Antwort

4

Sie tun können so etwas wie diese:

public static ExpandoObject Extend<T>(this T obj) 
{ 
    dynamic eo = new ExpandoObject(); 
    var props = eo as IDictionary<string, object>; 

    PropertyInfo[] pinfo = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance); 
    foreach (PropertyInfo p in pinfo) 
     props.Add(p.Name, p.GetValue(obj)); 

    //If you need to add some property known at compile time 
    //you can do it like this: 
    eo.SomeExtension = "Some Value"; 

    return eo; 
} 

Dies ermöglicht es Ihnen, dies zu tun:

var p = new { Prop1 = "value 1", Prop2 = 123 }; 
dynamic obj = p.Extend(); 

Console.WriteLine(obj.Prop1);   // Value 1 
Console.WriteLine(obj.Prop2);   // 123 
Console.WriteLine(obj.SomeExtension); // Some Value 
+1

Großen answe Danke. –

Verwandte Themen