为什么以及何时继承Collection& lt; T& gt; [英] Why and when to inherit from Collection<T>
问题描述
我正在用C#编写的项目中跟踪遗留代码.
I'm tracing legacy code in my project written in C#.
我找到以下代码:
public class FooCollection : Collection<IFoo> {};
我不明白为什么(和何时)需要创建这样的Collection类.
I don't understand why (and when) we need to create our own Collection class like this.
为什么不只使用内置集合( array
, List< T>
, Dictionary< K,V>
,..)
Why not just use the build-in collection (array
, List<T>
, Dictionary<K,V>
, ...)
Collection< T>
中使用的数据结构是什么?大批?或链表?
What's the data structure used in Collection<T>
?? array? or linked list?
推荐答案
我不明白为什么(和何时)需要创建这样的Collection类.
I don't understand why (and when) we need to create our own Collection class like this.
您并不是真的需要";您可以直接直接使用 Collection< IFoo>
,但是拥有特定的类可以提高可读性.
You don't really "need" to; you could just use Collection<IFoo>
directly, but having a specific class can help readability.
此外,它允许您为此集合类型添加特定的行为,因为 Collection< T>
类允许通过重写虚拟方法来重新定义大多数操作;这使您可以自定义标准收集方法的行为.
Also, it allows you to add specific behavior for this collection type as the Collection<T>
class allows most operations to be redefined by overriding virtual methods; this allows you to customize the behavior of the standard collection methods.
因此,例如,当您不能直接覆盖 Add
方法时,可以覆盖 InsertItem
,然后由 Add
, AddRange
等.
So, for example, while you cannot directly override the Add
method, you can override InsertItem
which is then used by Add
, AddRange
etc.
为什么不只使用内置集合(数组,列表,字典等)
Why not just use the build-in collection (array, List, Dictionary, ...)
数组的长度是固定的,因此您不能添加或删除项目.所以这不是真正的等价物. Dictionary< K,V>
将值与键相关联,因此它具有明显不同的用途.只要您不需要自定义行为,就可以使用 List< T>
来代替.此类不是为继承而设计的,因为它的方法是非虚拟的.
An array has a fixed length, so you can't add or remove items; so it's not really equivalent. Dictionary<K,V>
associates a value with a key, so it has a clearly different purpose. List<T>
could be used instead, as long as you don't need to customize the behavior; this class is not designed for inheritance, since its methods are non-virtual.
Collection中使用的数据结构是什么?大批?或链表?
What's the data structure used in Collection ?? array? or linked list?
Collection< T>
充当另一个 IList< T>
的包装.默认情况下,它使用 List< T>
(基于数组),但是您可以将任何其他 IList< T>
实现传递给构造函数,并且它会改用它.
Collection<T>
acts as a wrapper around another IList<T>
. By default, it uses a List<T>
(which is based on an array), but you can pass any other IList<T>
implementation to the constructor, and it will use that instead.
这篇关于为什么以及何时继承Collection& lt; T& gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!