如何创建具有inheritance的generics类?
如何使以下代码有效? 我不认为我完全理解C#generics。 也许,有人可以指出我正确的方向。
public abstract class A { } public class B : A { } public class C : A { } public static List GetCList() { return new List(); } static void Main(string[] args) { List listA = new List(); listA.Add(new B()); listA.Add(new C()); // Compiler cannot implicitly convert List listB = new List(); // Compiler cannot implicitly convert List listC = GetCList(); // However, copying each element is fine // It has something to do with generics (I think) List listD = new List(); foreach (B b in listD) { listB.Add(b); } }
这可能是一个简单的答案。
更新:首先,这在C#3.0中是不可能的,但在C#4.0中是可能的。
要使它在C#3.0中运行,这只是一种解决方法,直到4.0,请使用以下命令:
// Compiler is happy List listB = new List().OfType().ToList(); // Compiler is happy List listC = GetCList().OfType().ToList();
你总能做到这一点
List testme = new List().OfType().ToList();
正如“Bojan Resnik”指出的那样,你也可以……
List testme = new List().Cast().ToList();
值得注意的是,如果一个或多个类型不匹配,Cast
这不起作用的原因是因为它无法确定是安全的。 假设你有
List giraffes = new List (); List 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());
嘿,你只是将一只乌龟放入长颈鹿名单中,现在已经违反了类型系统的完整性。 这就是为什么这是非法的。
这里的关键是“动物”和“长颈鹿”指的是相同的对象,而该对象是长颈鹿的列表。 但是长颈鹿的名单不能像动物名单那么多; 特别是它不能包含乌龟。