从 List<T> 继承 [英] Inheriting from List&lt;T&gt;

查看:27
本文介绍了从 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>.

这受到框架设计指南的支持,更具体地说:

不要使用ArrayListListHashtableDictionary公共 API.使用 CollectionReadOnlyCollection,KeyedCollection,或取而代之的是 CollectionBase 子类型.笔记泛型集合只是Framework 2.0 版支持及以上.

DO NOT use ArrayList, List<T>, Hashtable, or Dictionary<K,V> in public APIs. Use Collection<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屋!

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