C# PropertyInfo(泛型)

4
假设我有这个类:
class Test123<T> where T : struct
{
    public Nullable<T> Test {get;set;}
}

并且这个类

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

那么,回到问题上来,假设我想通过反射创建一个名为“Test321”的实例,并将“Test”设置为一个值,我如何获取泛型类型?

3个回答

16

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

当然可以这样做,但是假设我不知道泛型参数是Int,我只知道Test321的类型。 - Peter

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上查看反射和泛型概述


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接