T&GT;从列表与LT继承; [英] Inheriting from List<T>
问题描述
什么是实现从继承名单℃的新类的最快方法; T&GT;
class Animal {}
class Animals : List<Animal> {} // (1)
一个问题我遇到:通过简单地做的(1)后,我发现我没有收到来自继承任何构造函数列表与LT的利益; T&GT ;
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>
.
在最后,我想动物
来表现很像列表&LT; T&GT;
(例如: ,可以构造兼容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.
推荐答案
如果你想创建一个公开曝光动物收集你不应该从列表与LT继承; T&GT;
,而是从 收藏&LT; T&GT;
,并使用在类名后缀收藏
。例如: AnimalCollection:收集&LT;动物&GT;
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
,列表&LT; T&GT;
,
的Hashtable
或词典&LT; K,V&GT;
中
公共API。使用收藏&LT; T&GT;
,
ReadOnlyCollection还&LT; T&GT;
,
KeyedCollection&LT; K,T&GT;
或
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.
这篇关于T&GT;从列表与LT继承;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!