public class BaseGenericType<T>
{
}
public class SubGenericType<T>: BaseGenericType<List<T>>
{
}
我上面有两个泛型,一个继承自另一个,但仍然是泛型。
我想不通的奇怪的是 typeof(SubGenericType<>).IsSubclassOf(typeof(BaseGenericType<>))
返回假。和 typeof(SubGenericType<>).IsSubclassOf(typeof(BaseGenericType<List<>>))
仍然返回错误。我试过了 GetGenericTypeDefinition()
和 MakeGenericType()
和 GetGenericArguments()
检查继承,仍然无法正常工作。但是typeof(SubGenericType<int>).IsSubclassOf(typeof(BaseGenericType<List<int>>))
返回真。
我想要的是通过反射获取所有类,然后获取从传入的泛型类型继承的特定类。
例如
(1)
List<int>
-->(2)get generic type definition ==>
List<T>
-->(3)make generic ==>
BaseGenericType<List<T>>
-->(4)find subclass ==>
SubGenericType<T>
(5)make generic ==>
SubGenericType<int>
在步骤 (4) 中,我什么也没找到,尽管我实际上有 SubGenericType<T>
.这是为什么?
最佳答案
一旦我写了这个方法来检查泛型类型继承:
static bool IsSubclassOfOpenGeneric(Type generic, Type toCheck)
{
while (toCheck != null && toCheck != typeof(object))
{
var cur = toCheck.IsGenericType ? toCheck.GetGenericTypeDefinition() : toCheck;
if (generic == cur)
{
return true;
}
toCheck = toCheck.BaseType;
}
return false;
}
返回真:
IsSubclassOfOpenGeneric(typeof(BaseGenericType<>), typeof(SubGenericType<int>))
虽然它不检查接口(interface)。
顺便说一句,通常如果你有这样的关系,并且你自己编写所有类,考虑使用接口(interface)。它更容易处理。例如,您可以有一个IGenericType
接口(interface)没有 泛型参数。有时您只是不关心泛型类型,只想访问不依赖于泛型类型的成员。有时您只想检查它是否是其中之一。 并且您可以使用类型差异。
关于c# - 泛型继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31106828/