2009-08-24 24 views
3

Können sagen, ich habe diese Klasse:C# Property (Generic)

class Test123<T> where T : struct 
{ 
    public Nullable<T> Test {get;set;} 
} 

und diese Klasse

class Test321 
{ 
    public Test123<int> Test {get;set;} 
} 

Also das Problem sagen lässt ich eine Test321 über Reflexion erstellen möchten und setzen Sie „Test "mit einem Wert wie bekomme ich den generischen Typ?

Antwort

13

Da Sie von Test321 Start sind, ist der einfachste Weg, um die Art der Immobilie zu erhalten: Sie

Type type = typeof(Test321); 
object obj1 = Activator.CreateInstance(type); 
PropertyInfo prop1 = type.GetProperty("Test"); 
object obj2 = Activator.CreateInstance(prop1.PropertyType); 
PropertyInfo prop2 = prop1.PropertyType.GetProperty("Test"); 
prop2.SetValue(obj2, 123, null); 
prop1.SetValue(obj1, obj2, null); 

Oder meinen Sie möchten die T finden?

Type t = prop1.PropertyType.GetGenericArguments()[0]; 
0

Dies sollte es mehr oder weniger tun. Ich habe momentan keinen Zugriff auf Visual Studio, aber es gibt Ihnen möglicherweise Hinweise, wie Sie den generischen Typ instanziieren und die Eigenschaft festlegen können.

// Define the generic type. 
var generic = typeof(Test123<>); 

// Specify the type used by the generic type. 
var specific = generic.MakeGenericType(new Type[] { typeof(int)}); 

// Create the final type (Test123<int>) 
var instance = Activator.CreateInstance(specific, true); 

Und den Wert zu setzen:

// Get the property info of the property to set. 
PropertyInfo property = instance.GetType().GetProperty("Test"); 

// Set the value on the instance. 
property.SetValue(instance, 1 /* The value to set */, null) 
+0

Sicher, das würde funktionieren, aber lässt sagen, ich weiß nicht, dass der generische Parameter Int ist .. alles, was ich weiß, ist der Typ von Test321. – Peter

0

so etwas wie dieses Versuchen:

using System; 
using System.Reflection; 

namespace test { 

    class Test123<T> 
     where T : struct { 
     public Nullable<T> Test { get; set; } 
    } 

    class Test321 { 
     public Test123<int> Test { get; set; } 
    } 

    class Program { 

     public static void Main() { 

      Type test123Type = typeof(Test123<>); 
      Type test123Type_int = test123Type.MakeGenericType(typeof(int)); 
      object test123_int = Activator.CreateInstance(test123Type_int); 

      object test321 = Activator.CreateInstance(typeof(Test321)); 
      PropertyInfo test_prop = test321.GetType().GetProperty("Test"); 
      test_prop.GetSetMethod().Invoke(test321, new object[] { test123_int }); 

     } 

    } 
} 

prüfen diese Overview of Reflection and Generics auf msdn.