LinkedList(T) 添加方法
ICollection(T) 接口中的 Add-方法已明确由 LinkedList(T)- 类实现。 该集合具有 AddFirst 和 AddLast 方法(以及其他方法)。 显式实现的方法映射到 AddLast 方法。 这有一些缺点,恕我直言,没有任何好处。 两个主要缺点是:
- 您不能在 LinkedList(T) 上使用集合初始化,因为它需要 Add 方法。
- 如果您在方法中使用了 List(T),并且想要将其更改为使用 LinkedList(T),则必须更新对 Add 的所有调用以调用 AddLast。
我的想法是,你不应该显式实现接口成员,除非当你知道具体类型时它们根本没有意义。 例如,如果您要实现只读 ICollection(T),则应显式实现(并有效隐藏)Add 方法。
是否还有其他已显式实现但不应该出现在框架中的方法示例?
附带说明:要解决第二个问题,您可以为 LinkedList(T) 类创建一个扩展方法“Add”。
The Add-method from the ICollection(T) interface has been explicitly implemented by the LinkedList(T)-class. This collection instead have AddFirst- and AddLast-methods (among others). The explicitly implemented method maps to the AddLast-method. This has some drawbacks and IMHO no benefit at all. The two major drawbacks are this:
- You can't use collection initialization on a LinkedList(T) since it requires an Add-method.
- If you have used let's say a List(T) in a method and want to change it to use a LinkedList(T) instead you'll have to update all calls to Add to call AddLast instead.
The way I think about it is that you should never explicitly implement interface members unless they make no sense at all when you know the concrete type. For example the Add-method should be explicitly implemented (and effectively hidden) if you were implementing a read only ICollection(T).
Are there other examples of methods that have been explicitly implemented that shouldn't have been in the framework?
As a side note: To resolve the number 2 issue you could create an extension method "Add" for the LinkedList(T)-class.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Add
方法是不明确的,所以我对显式实现感到满意...Queue[]
和Stack[; ]
有类似的行为。对于其他(非集合)好奇的显式成员 -
DbParameter 怎么样。精度
和DbParameter.Scale
。
关于两者之间转移的问题 - 您始终可以在
IEnumerable
上编写ToLinkedList
扩展方法。或者 -
AddRange
扩展方法有很长的路要走...(编辑)如果您希望能够使用,您也可以使用“流畅”的 API将其作为单个表达式:
The
Add
method would be ambiguous, so I'm content with an explicit implementation...Queue[<T>]
andStack[<T>]
have similar behaviour.For other (non-collection) curious explicit members - how about
DbParameter.Precision
andDbParameter.Scale
.Re the issue transferring between the two - you could always write a
ToLinkedList<T>
extension method onIEnumerable<T>
.Alternatively - an
AddRange<T>
extension method goes a long way...(EDIT) You could also use a "fluent" API if you want to be able to use it as a single expression: