public class ClassWithGeneric<T>
{
}
public class SecondClassWithGeneric<U>
{
public void getNestedObject()
{
//How do I get the type of object T?
}
}
public class TestProgram
{
var nestedGenerics = new SecondClassWithGeneric<ClassWithGeneric<ObjectToLoad>>;
}
public class ObjectToLoad
{
}
问题是如何获得对象T的类型?在这种情况下,它将返回&#34; ObjectToLoad&#34;。
答案 0 :(得分:3)
不太清楚但可能:
public class SecondClassWithGeneric<U, T>
where U : ClassWithGeneric<T>
{
public T getNestedObject()
{
//How do I get the type of object T?
}
}
或者
public class SecondClassWithGeneric<U, T>
{
public ClassWithGeneric<T> getNestedObject()
{
//How do I get the type of object T?
}
}
答案 1 :(得分:0)
这应该为您提供ObjectToLoad
类型,但它也很容易出错。
public class SecondClassWithGeneric<U>
{
public void getNestedObject()
{
var type = typeof(U).GetGenericArguments()[0];
}
}