链表中不包含明确的Add方法 [英] LinkedList does not contain explicit Add method

查看:114
本文介绍了链表中不包含明确的Add方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现的LinkedList<的有趣的行为; T> 。我不能叫添加方法的LinkedList<的实例;>。然而的LinkedList< T> 工具的ICollection< T> 链接),它实际上有Add方法。

I found interesting behavior of LinkedList<T>. I can't call Add method for an instance of LinkedList<>. However LinkedList<T> implements ICollection<T> (link) which actually has the Add method.

下面就是例子。当我做这样的,它完美的作品:

Here are examples. When I do like this, it works perfect:

ICollection<string> collection = new LinkedList<string>();
collection.Add("yet another string");



不过,这段代码甚至不会编译:

But this code even will not compile:

LinkedList<string> linkedList = new LinkedList<string>();
linkedList.Add("yet another string");



编译器说:
无法访问明确实行ICollection.Add'
错误CS1061链表不包含添加的定义,并没有扩展方法添加接受式的LinkedList的第一个参数可以找到(是否缺少using指令或程序集引用?)

Compiler says: "Can not access explicit implementation of 'ICollection.Add' "Error CS1061 'LinkedList' does not contain a definition for 'Add' and no extension method 'Add' accepting a first argument of type 'LinkedList' could be found (are you missing a using directive or an assembly reference?)"

此外,如果看的LinkedList的,它的实施方法。
所以我的问题是,这怎么可能呢?

Moreover if to look at the sources of LinkedList, it implements the method. So my question is, how can it be?

推荐答案

该方法实施的明确的按该错误消息意味着显式转换给定的接口需要在你的第二个例子,这将工作:

The method is implemented explicitly as per the error message. That means an explicit cast to the given interface is required. In your second example this will work:

((ICollection<string>)linkedList).Add("yet another string");

有关的任​​何使用此技术的接口的实现者可以选择的的使某个接口的方法和属性的部分原因。的class'es人,公共接口

For whatever reason using this technique the implementer of an interface may choose not to make certain interface methods and properties part of the class'es native, public interface.

的LinkedList<的情况下,T> 类,笔者显然首选的所有可能类型的添加功能的cannonical命名方案(即(而不是简单的添加 addfirst仅 / addlast仅 / AddBefore / AddAfter ),在使抽象集合接口直接访问。然而,由于显式实现兼容与期望呼叫者的的ICollection< T> 仍然维持,其添加是翻译成 addlast仅通话这是respet合乎逻辑的的ICollection< T> 的合同。 (虽然这样的设计决策的评价是主观的,让我补充我认为这是一件好事。)

In case of the LinkedList<T> class, the author apparently preferred a cannonical naming scheme for all possible types of 'add' functionality (i.e. AddFirst / AddLast (instead of plain Add) / AddBefore / AddAfter) over making the abstract collection interface directly accessible. However, thanks to explicit implementation compatibility with callers that expect an ICollection<T> is still maintained, and its Add is translated to an AddLast call which is logical in respet to ICollection<T>'s contract. (While the evaluation of such design decision is subjective, let me add I consider it a good thing.)

这篇关于链表中不包含明确的Add方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆