[英]How to test if Type derives from an abstract base generic type?
Hey I have an abstract generic type BList<TElement> where TElement : Career
. 嘿,我有一个抽象的通用类型BList<TElement> where TElement : Career
。 Career is abstract type too. 职业也是抽象类型。
Given a type T, how do I test if it is a BList type? 给定类型T,如何测试它是否为BList类型? And how can I cast to the base class? 我怎样才能投入基类? I tried (BList<Career>)object
but the compiler was upset. 我试过(BList<Career>)object
但编译器很不高兴。 Apparently I can't write BList<Career>
because Career is abstract. 显然我不能写BList<Career>
因为职业是抽象的。
There's a bit of ambiguity with your question, so I'll attempt to answer some of the things i think you may be asking... 你的问题有些含糊不清,所以我会尝试回答一些我认为你可能要问的事情......
If you want to check if an instance T
is a BList you can just use is
: 如果你想检查一个实例T
是BList你可以使用is
:
if (someInstance is BList<Career>)
{
...
}
If you want to see if a generic type parameter is a BList<Career>
you can use typeof
: 如果要查看泛型类型参数是否为BList<Career>
,可以使用typeof
:
if (typeof(T) == typeof(BList<Career>)
{
...
}
But, if you are just wanting to see if it's any BList<>
, you can use reflection: 但是,如果你只是想看看它是否是任何 BList<>
,你可以使用反射:
var t = typeof(T); // or someInstance.GetType() if you have an instance
if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(BList<>))
{
...
}
Now, as far as how do you cast a BList<TElement>
to a BList<Career>
? 现在,就如何将BList<TElement>
转换为BList<Career>
? You can't safely. 你不能安全。
This has nothing to do with Career
being abstract, it has to do with the fact that BList<Career>
does not inherit from BList<TElement>
even though Career
inherits from TElement
. 这有没有关系Career
是抽象的,它与事实做BList<Career>
不继承BList<TElement>
尽管Career
从继承TElement
。
Consider this: 考虑一下:
public class Animal { }
public class Dog : Animal { }
public class Cat : Animal { }
Given those, ask yoruself why does this not work: 鉴于这些,请问yoruself为什么这不起作用:
List<Animal> animals = new List<Cat>();
See the problem? 看到问题? If we allow you to cast a List<Cat>
to a List<Animal>
, then all of the sudden the Add()
method will support Animal
instead of Cat
, which means you could do this: 如果我们允许您将List<Cat>
转换为List<Animal>
,那么突然Add()
方法将支持Animal
而不是Cat
,这意味着您可以这样做:
animals.Add(new Dog());
Clearly, there is no way we should be able to add a Dog
to a List<Cat>
. 显然,我们无法将Dog
添加到List<Cat>
。 This is why you can't use a List<Cat>
as a List<Animal>
even though Cat
inherits from Animal
. 这就是为什么你不能使用List<Cat>
作为List<Animal>
即使Cat
继承自Animal
。
Similar case here. 这里类似的情况。
var item = theObject as BList<Career>;
如果它为null
则不是那种类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.