[英]How to make a generic class with inheritance?
如何使以下代码起作用? 我认为我不太了解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<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());
嘿,您只将乌龟放入了长颈鹿列表中,现在已经侵犯了类型系统的完整性。 这就是为什么这是非法的。
这里的关键是“动物”和“长颈鹿”是指“相同对象”,而该对象是长颈鹿的列表。 但是,长颈鹿清单不能像动物清单那样多。 特别是它不能包含乌龟。
你总是可以这样做
List<A> testme = new List<B>().OfType<A>().ToList();
正如“ Bojan Resnik”所指出的,您还可以...
List<A> testme = new List<B>().Cast<A>().ToList();
需要注意的区别是,如果一种或多种类型不匹配,Cast <T>()将失败。 其中OfType <T>()将返回仅包含可转换对象的IEnumerable <T>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.