本文介绍了C# List&lt;Interface&gt;:为什么不能做`List&lt;IFoo&gt;foo = new List<Bar>();`的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果你有一个接口 IFoo 和一个类 Bar : 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());

但你不能这样做:

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 是一个 List,这意味着它可以采用 IFoo 的任何实例.然而,这与它被实例化为 List 的事实相冲突.由于拥有 List 意味着我可以添加 Zed 的新实例,我们不能允许这样做,因为底层列表实际上是 List;,不能容纳 Zed.

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# List&lt;Interface&gt;:为什么不能做`List&lt;IFoo&gt;foo = new List<Bar>();`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 09:18