C#PropertyInfo(Generic)

时间:2009-08-24 07:36:07

标签: c# reflection

假设我有这门课程:

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

和这个班级

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

所以对于这个问题,我想说我想通过反射创建一个Test321并用一个值设置“Test”如何获得泛型类型?

3 个答案:

答案 0 :(得分:15)

由于您从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];

答案 1 :(得分: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)

答案 2 :(得分: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 });

        }

    }
}

在msdn。

上查看Overview of Reflection and Generics