从 List<T> 继承 [英] Inheriting from List<T>
问题描述
实现从List
继承的新类的最快方法是什么?
What is the fastest way to implement a new class that inherits from List<T>
?
class Animal {}
class Animals : List<Animal> {} // (1)
我遇到的一个问题:通过简单地执行 (1),我发现我没有从 List
One problem I've encountered: By simply doing (1), I've found that I'm not getting the benefit of inheriting any constructors from List<T>
.
最后,我希望 Animals
的行为很像 List
(例如,可以构造,与 Linq 兼容).但除此之外,我还希望能够添加自己的自定义方法.
In the end, I'd like Animals
to behave a lot like a List<T>
(e.g., can be constructed, compatibility with Linq). But in addition, I'd also like to be able to add my own custom methods.
推荐答案
如果你想创建一个公开暴露的动物集合,你不应该从List
继承而是从 Collection
继承并在类名中使用后缀 Collection
.示例:AnimalCollection : Collection
.
If you want to create a publicly exposed animal collection you should not inherit from List<T>
and instead inherit from Collection<T>
and use the postfix Collection
in the class name. Example: AnimalCollection : Collection<Animal>
.
这受到框架设计指南的支持,更具体地说:
不要使用ArrayList
、List
、Hashtable
或 Dictionary
公共 API.使用 Collection
,ReadOnlyCollection
,KeyedCollection
,或取而代之的是 CollectionBase 子类型.笔记泛型集合只是Framework 2.0 版支持及以上.
DO NOT use
ArrayList
,List<T>
,Hashtable
, orDictionary<K,V>
in public APIs. UseCollection<T>
,ReadOnlyCollection<T>
,KeyedCollection<K,T>
, or CollectionBase subtypes instead. Note that the generic collections are only supported in the Framework version 2.0 and above.
这篇关于从 List<T> 继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!