簡體   English   中英

如何測試Type是否從抽象基類泛型類型派生?

[英]How to test if Type derives from an abstract base generic type?

嘿,我有一個抽象的通用類型BList<TElement> where TElement : Career 職業也是抽象類型。

給定類型T,如何測試它是否為BList類型? 我怎樣才能投入基類? 我試過(BList<Career>)object但編譯器很不高興。 顯然我不能寫BList<Career>因為職業是抽象的。

你的問題有些含糊不清,所以我會嘗試回答一些我認為你可能要問的事情......

如果你想檢查一個實例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>盡管Career從繼承TElement

考慮一下:

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> 這就是為什么你不能使用List<Cat>作為List<Animal>即使Cat繼承自Animal

這里類似的情況。

var item = theObject as BList<Career>;  

如果它為null則不是那種類型。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM