Ami*_*atz 2 c# generics inheritance
为什么这不会编译?也许FW5可以实现......
static void Main(string[] args)
{
List<Foo> foos = new List<Goo>();
}
public class Foo
{
}
public class Goo : Foo
{
}
Run Code Online (Sandbox Code Playgroud)
Stackover流程说我的帖子主要是代码......但那可能有问题所以我试图通过代码文本比率验证....希望这就够了
现在它说我没有正确描述这个问题..再次阅读它似乎很好我...
由于名单Goo是没有的名单Foo.如果有效,你可以(在编译时):
foos.Add(new Foo());
Run Code Online (Sandbox Code Playgroud)
这显然无法工作,因为列表只能采用Goo实例.
方差确实存在(取决于框架版本),但是受限于:接口和委托(不是像列表这样的具体类型),以及b:到已知全部"进入"或已知全部"出"情形.
例如,以下内容将在最近的框架/编译器版本上进行编译:
IEnumerable<Goo> goos = new List<Goo>();
IEnumerable<Foo> foos = goos;
Run Code Online (Sandbox Code Playgroud)
在这种情况下,它工作正常,因为每个Goo静态已知是一个Foo.从技术上讲,这使用了签名out部分IEnumerable<out T>.
您不被允许这样做的原因是它允许这样的代码:
public class Mammal {}
public class Cat: Mammal {}
public class Dog: Mammal {}
...
List<Cat> cats = new List<Cat>();
List<Mammal> mammals = cats; // Imagine this compiles.
mammals.Add(new Dog()); // We just added a dog to the list of cats!
Run Code Online (Sandbox Code Playgroud)