C#List< Interface>:为什么你不能`List< IFoo> foo =新列表< Bar>();`

编程入门 行业动态 更新时间:2024-10-28 18:27:09
本文介绍了C#List< Interface>:为什么你不能`List< IFoo> foo =新列表< 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());

但是你不能这样做:

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 是一个 List< IFoo> ,这意味着它可以接受 IFoo 的任何实例。但是,这与它被实例化为 List< Bar> 的事实相冲突。由于有一个 List< IFoo> ,这意味着我可以添加一个新的 Zed 实例,所以我们不能允许因为底层列表实际上是 List< Bar> ,它无法容纳 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 =新列表&l

本文发布于:2023-11-11 11:52:51,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:列表   lt   Interface   List   amp

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!