嘿,我有一个抽象的泛型类型BList<TElement> where TElement : Career.职业也是抽象类型.
给定类型T,如何测试它是否为BList类型?我怎样才能投入基类?我试过(BList<Career>)object但编译器很不高兴.显然我不能写,BList<Career>因为职业是抽象的.
你的问题有些含糊不清,所以我会尝试回答一些我认为你可能要问的事情......
如果要检查实例T是否为BList,您可以使用is:
if (someInstance is BList<Career>)
{
...
}
Run Code Online (Sandbox Code Playgroud)
如果要查看泛型类型参数BList<Career>是否可以使用typeof:
if (typeof(T) == typeof(BList<Career>)
{
...
}
Run Code Online (Sandbox Code Playgroud)
但是,如果你只是想知道它是否是任何 BList<>,你可以使用反射:
var t = typeof(T); // or someInstance.GetType() if you have an instance
if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(BList<>))
{
...
}
Run Code Online (Sandbox Code Playgroud)
现在,至于你如何投了BList<TElement>一个BList<Career>?你不能安全.
这有没有关系Career是抽象的,它有一个事实做BList<Career>并没有继承BList<TElement>但即使Career继承TElement.
考虑一下:
public class Animal { }
public class Dog : Animal { }
public class Cat : Animal { }
Run Code Online (Sandbox Code Playgroud)
鉴于这些,请问yoruself为什么这不起作用:
List<Animal> animals = new List<Cat>();
Run Code Online (Sandbox Code Playgroud)
看到问题?如果我们允许你将a转换List<Cat>为a List<Animal>,那么突然之间该Add()方法将支持Animal而不是Cat,这意味着你可以这样做:
animals.Add(new Dog());
Run Code Online (Sandbox Code Playgroud)
显然,我们无法添加Dog到a List<Cat>.这就是为什么你不能使用a List<Cat>作为一个List<Animal>即使Cat继承Animal.
这里类似的情况.
| 归档时间: |
|
| 查看次数: |
638 次 |
| 最近记录: |