如何使继承一个泛型类?
-
23-08-2019 - |
题
我怎样才能让下面的代码工作?我不认为我很明白C#泛型。也许,有人可以点我在正确的方向。
public abstract class A
{
}
public class B : A
{
}
public class C : A
{
}
public static List<C> GetCList()
{
return new List<C>();
}
static void Main(string[] args)
{
List<A> listA = new List<A>();
listA.Add(new B());
listA.Add(new C());
// Compiler cannot implicitly convert
List<A> listB = new List<B>();
// Compiler cannot implicitly convert
List<A> listC = GetCList();
// However, copying each element is fine
// It has something to do with generics (I think)
List<B> listD = new List<B>();
foreach (B b in listD)
{
listB.Add(b);
}
}
这可能是一个简单的答案。
更新: 首先,这不是在C#3.0可能的,但将有可能在C#4.0。
要得到它运行在C#3.0,这仅仅是一种变通方法,直到4.0,使用下列:
// Compiler is happy
List<A> listB = new List<B>().OfType<A>().ToList();
// Compiler is happy
List<A> listC = GetCList().OfType<A>().ToList();
解决方案
你总是可以做到这一点。
List<A> testme = new List<B>().OfType<A>().ToList();
由于“博扬雷斯尼克”指出的那样,你也可以做......
List<A> testme = new List<B>().Cast<A>().ToList();
要注意的区别在于角色
其他提示
这不工作的原因是因为它无法确定是安全的。假设你有
List<Giraffe> giraffes = new List<Giraffe>();
List<Animal> animals = giraffes; // suppose this were legal.
// animals is now a reference to a list of giraffes,
// but the type system doesn't know that.
// You can put a turtle into a list of animals...
animals.Add(new Turtle());
哎,你只要把乌龟变成长颈鹿的名单,现在的类型系统的完整性受到了侵犯。这就是为什么这是非法的。
这里的关键是,“动物”和“长颈鹿”指的是同一个对象,并且该对象是长颈鹿的列表。但是,长颈鹿的列表不能做尽可能多的动物可以做的列表;特别是,它不能包含龟
不隶属于 StackOverflow