收藏< T>类和它的使用 [英] Collection<T> class and it's use

查看:109
本文介绍了收藏< T>类和它的使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我碰到下面的code:

  VAR集合=新的集合<字符串>();
 

我还没有看到使用的集合类太多了,找不到关于它的目的太多的信息。纵观.NET Framework源,这是pretty的多少只是一个包装围绕一个列表,因为它存储列表成员字段。它的构造函数如下:

 公文集()
{
  this.items =(IList的< T>)的新名单,其中,T>();
}
 

和它也实现IList。所以,你可以声明集合为:

 的IList<字符串>集合=新的集合<字符串>();
 

这对我来说是功能上等同于创建一个列表,而不是:

 的IList<字符串>集合=新的名单,其中,串>();
 

因此​​,当将你想用它在一个列表,你自己的code?我看,这是对其他.NET集合的基类,但是为什么他们有这个作为公开具体(相对于内部和/或抽象的)?


关于周围可能重复注释的 - 的答案相关的问题似乎说集合类应该被用作基类。我真正要求将不同的是:

  1. 如果使用自己的code,为什么不使用列表作为基类来代替?
  2. 在它是否真的曾经是有意义的实例化一个新的集合在 你自己的code代替列表?
  3. 如果真的是提供给作为基类,为什么它不是抽象的
解决方案

我真的不喜欢回答我自己的问题,但就第三季度而言,我相信我理解的理由。我得到了它在此链接在巴斯PAAP的回答引用。

总之,集合类不是抽象的原因是因为你可能要离开自己的派生类在日后的选项。在此期间,你可以使用它作为返回类型,并直接进行实例化。 链接显示了$ C $℃实施例,其中是这种情况。

我upvoted,我认为解决的问题,提出的问题的所有答案。

I came across the following code:

var collection = new Collection<string>();

I haven't seen the Collection class used too much, and can't find too much information about its purpose. Looking at the .NET Framework source, it's pretty much just a wrapper around a List as it stores a List member field. Its constructor is as follows:

public Collection()
{
  this.items = (IList<T>) new List<T>();
}

And it also implements IList. So you can declare the Collection as:

IList<string> collection = new Collection<string>();

Which to me is functionally equivalent to creating a List instead:

IList<string> collection = new List<string>();

So when would you ever want to use it over a List in your own code? I see that it is a base class for other .NET collections, but why would they include this as a public concrete (as opposed to internal and/or abstract)?


Regarding comments around possible duplicates -- the answers to related questions seem to say that Collection class is supposed to be used as a base class. What I'm really asking that's different is:

  1. If using in your own code, why not use List as a base class instead?
  2. Does it really ever make sense to instantiate a new Collection in your own code in place of List?
  3. If it really is only provided to serve as a base class, why is it not abstract?

解决方案

I don't really like answering my own questions, but as far as Q3 is concerned I believe I understand the reasoning. I got it while looking at this link referenced in Bas Paap's answer.

In short, the reason the Collection class is not abstract is because you may want to leave yourself the option of deriving from the class at a later date. In the meantime, you can use it as a return type and instantiate it directly. The link shows a code example where this is the case.

I've upvoted all other answers that I thought addressed the issues raised in the question.

这篇关于收藏&LT; T&GT;类和它的使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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