假设我有这门课:
class Test123<T> where T : struct
{
public Nullable<T> Test {get;set;}
}
和这个类
class Test321
{
public Test123<int> Test {get;set;}
}
所以对于这个问题,假设我想通过反射创建一个 Test321 并为“Test”设置一个值,我如何获得通用类型?
最佳答案
由于您是从 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];
关于C# PropertyInfo(通用),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1320934/