2012-09-26 48 views
4

嘿,我有一个抽象泛型BList<TElement> where TElement : Career。职业也是抽象类型。如何测试类型是否来自抽象基类型?

给定类型T,如何测试它是否是BList类型?我该如何投入基础课程?我试过(BList<Career>)object,但编译器很不高兴。显然我不能写BList<Career>因为职业是抽象的。

+2

你应该可以使用'is'运算符 –

+1

显示你的代码。 “编译器不高兴”不会告诉我们很多。 –

回答

8

有一点你的问题的模糊性,所以我会尝试回答的一些事情,我认为你可能会问...

如果你想检查是否一个实例T是BList你可以只使用is

if (someInstance is BList<Career>) 
{ 
... 
} 

如果你想看看一个泛型类型参数是一个BList<Career>你可以使用typeof

if (typeof(T) == typeof(BList<Career>) 
{ 
... 
} 

但是,如果你只是想看看它是否任何BList<>,你可以使用反射:

var t = typeof(T); // or someInstance.GetType() if you have an instance 

if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(BList<>)) 
{ 
    ... 
} 

现在,只要你如何投下BList<TElement>BList<Career>?你不能安全。

这有什么好做Career是抽象的,它与事实BList<Career>继承BList<TElement>TElement即使Career继承做。

考虑一下:

public class Animal { } 

public class Dog : Animal { } 

public class Cat : Animal { } 

鉴于这些,问yoruself为什么这不工作:

List<Animal> animals = new List<Cat>(); 

看这个问题?如果我们让你蒙上了List<Cat>List<Animal>,那么所有的突然的Add()方法将支持Animal代替Cat,这意味着你可以这样做:

animals.Add(new Dog()); 

显然,没有办法,我们应该是能够将Dog添加到List<Cat>。这就是为什么即使Cat继承自Animal,也不能使用List<Cat>作为List<Animal>

类似的情况在这里。

+0

谢谢当我试图问我的问题时,我都感到困惑。现在我明白了。 –

+0

@ColonelPanic:没问题!很高兴我能帮上忙! –

1
var item = theObject as BList<Career>; 

如果是null那么它是该类型的不行。