为什么和何时从Collection< T>继承 [英] Why and when to inherit from Collection<T>

查看:79
本文介绍了为什么和何时从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.

为什么不只使用内置集合(数组 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?

推荐答案


我不明白为什么(以及何时)需要创建

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屋!

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