2009-08-24 45 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上。