C#新手名单<接口与GT;题 [英] C# newbie List<Interface> question
问题描述
如果你有一个接口的IFoo
和类酒吧:的IFoo
,为什么你能做到以下几点:
列表<的IFoo>富=新的List<的IFoo>();
foo.Add(新酒吧());
但你不能做的:
列表<的IFoo>富=新的List<酒吧及GT;();
在一个偶然一瞥,看来这应的(如啤酒的应的是免费的)工作。然而,快速全面的检查告诉我们为什么不能。请记住,下面的代码的不会编译。它意在表明它为什么不允许,即使它的看起来的好了起来,直到一个点。
公共接口的IFoo {}
公共类酒吧:的IFoo {}
公共类泽德:的IFoo {}
// .....
文件清单<的IFoo> myList中=新名单<酒吧及GT;(); //有意义迄今
myList.Add(新栏()); // OK,因为酒吧实现的IFoo
myList.Add(捷思锐新()); // AAAH!现在我们知道为什么。
// .....
myList中
是列表<的IFoo>
,这意味着它可以采取的IFoo
的任何实例。然而,这种冲突的事实,它被实例化列表<酒吧GT;
。由于具有列表<的IFoo>
意味着我可以添加捷思锐
的新实例,我们不能让因为底层名单实际上是列表<酒吧方式>
,不能容纳捷思锐
If you have an Interface IFoo
and a class Bar : IFoo
, why can you do the following:
List<IFoo> foo = new List<IFoo>();
foo.Add(new Bar());
But you cannot do:
List<IFoo> foo = new List<Bar>();
At a casual glance, it appears that this should (as in beer should be free) work. However, a quick sanity check shows us why it can't. Bear in mind that the following code will not compile. It's intended to show why it isn't allowed to, even though it looks alright up until a point.
public interface IFoo { }
public class Bar : IFoo { }
public class Zed : IFoo { }
//.....
List<IFoo> myList = new List<Bar>(); // makes sense so far
myList.Add(new Bar()); // OK, since Bar implements IFoo
myList.Add(new Zed()); // aaah! Now we see why.
//.....
myList
is a List<IFoo>
, meaning it can take any instance of IFoo
. However, this conflicts with the fact that it was instantiated as List<Bar>
. Since having a List<IFoo>
means that I could add a new instance of Zed
, we can't allow that since the underlying list is actually List<Bar>
, which can't accommodate a Zed
.
这篇关于C#新手名单<接口与GT;题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!