How to make a generic class with inheritance?

旧城冷巷雨未停 提交于 2019-11-29 12:30:50

you could always do this

List<A> testme = new List<B>().OfType<A>().ToList();

As "Bojan Resnik" pointed out, you could also do...

List<A> testme = new List<B>().Cast<A>().ToList();

A difference to note is that Cast<T>() will fail if one or more of the types does not match. Where OfType<T>() will return an IEnumerable<T> containing only the objects that are convertible

The reason this does not work is because it cannot be determined to be safe. Suppose you have

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());  

And hey, you just put a turtle into a list of giraffes, and the type system integrity has now been violated. That's why this is illegal.

The key here is that "animals" and "giraffes" refer to the SAME OBJECT, and that object is a list of giraffes. But a list of giraffes cannot do as much as a list of animals can do; in particular, it cannot contain a turtle.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!