2009-08-24 43 views
3

可以說我有這個類:C#的PropertyInfo(通用)

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

這個類

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

所以這個問題可以說,我想通過反射創建一個Test321,並設置「測試「具有價值,我如何獲得泛型?

回答

13

既然你是從Test321開始,要獲得類型的最簡單方法是從屬性:

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

還是你的意思你想找到T

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

這應該或多或少。我現在無法訪問Visual Studio,但它可能會給你一些線索,如何實例化泛型類型並設置屬性。

// 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); 

,並設定值:

// 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

當然會工作,但讓我說我不知道​​泛型參數是INT ..我所知道的是Test321的類型。 – Peter 2009-08-24 07:47:30

0

嘗試是這樣的:

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

     } 

    } 
} 

入住這Overview of Reflection and Generics MSDN上。