28

我需要设计自己的自定义GenericCollection类。现在我有很多选项可以使用IEnumerableICollection和派生它IList,稍后会提供一些附加功能。

我有点困惑,如果我一起去,IEnumerable<T>我可能需要声明对象以实际保存集合,就像在这种情况下一样_list

public class GenericCollection<T> : IEnumerable<T>
{
    private List<T> _list;
    //...
}

但是如果我使用ICollection<T>or IList<T>,我不需要声明List对象,因为它是隐式可用的。

public class GenericCollection<T> : IList<T>
{
    // no need for List object
    //private List<T> _list; 
    //...
}

这两种方法在性能方面有什么区别?

在哪种情况下,每一个都是首选,尤其是在设计您自己的系列时。我对性能良好的轻量级系列感兴趣。我认为这可以通过使用来实现,IEnumerable<T>但是究竟有什么强有力的理由去使用它呢?

我已经查看了一些现有的帖子,但没有一个提供所需的信息。

返回'IList' vs 'ICollection' vs 'Collection'

4

3 回答 3

65

IEnumerable, ICollection, and IList (generally, any type with an I prefix) are just interfaces. They let you expose what your class will do, but unlike if you inherit a class, interfaces do not provide you a default implementation of any of the things they say you must do.

As far as choosing which interface, here's a quick guide:

  • An IList is an ICollection that can be accessed by index.
  • An ICollection is an IEnumerable with easy access to things like Add, Remove, and Count.
  • An IEnumerable is anything that can be enumerated, even if the list of those things doesn't exist until you enumerate it.

Some classes that you might want to extend (or keep as a private field that runs most of the logic) for your collection are List<T>, Collection<T>, (which implements IList<T>, but with easier access to overriding implementation, see Collection<T> versus List<T> what should you use on your interfaces? for the big differences between these two) ObservableCollection<T>, or collections that are not lists, like Dictionary<T, U> and HashSet<T>. For more info on any of these, look up the MSDN documentation on the class.

于 2012-10-31T11:57:29.050 回答
1

首先,您不必在这些接口之间进行实际选择,如果有必要,您可以实现所有三个接口。其次,实现 IEnumerable 不需要您公开基础列表。您可以只实现使用基础列表的 Enumerator 的方法。

在性能方面,我怀疑会有很大的影响,专注于你在功能上需要的东西。唯一确定的方法是测量。

于 2012-10-31T11:51:59.800 回答
0

性能不太可能取决于实现了哪些接口。这取决于处理器必须运行多少指令才能实现某个目标。如果您实现 IEnumerable 并覆盖 List,您最终可能会编写 Add/Remove/this[] 方法,这些方法只是将调用传播到 List,这会增加性能开销。因此,虽然我没有进行任何测量,但继承方法可能会快一点。

然而,这些细节通常只对需要节省所有可能的 CPU 周期的实时应用程序很重要。Eric Lippert 有一篇关于关注此类细节的精彩文章:http: //blogs.msdn.com/b/ericlippert/archive/2003/10/17/53237.aspx。通常,您可能会更好地使用更适合您的应用程序的业务逻辑和架构的方法,而不是性能细节。

于 2012-10-31T11:50:48.677 回答