C#:List<T> 之间的区别和收藏<T>(CA1002,不要公开通用列表) [英] C#: Difference between List<T> and Collection<T> (CA1002, Do not expose generic lists)

查看:13
本文介绍了C#:List<T> 之间的区别和收藏<T>(CA1002,不要公开通用列表)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试在此处对项目运行运行代码分析,并收到许多警告,内容如下:

Tried to run Run Code Analysis on a project here, and got a number of warnings that said something like this:

CA1002:Microsoft.Design:将SomeClass.SomeProtectedOrPublicProperty"中的List<SomeType>"更改为使用 Collection、ReadOnlyCollection 或 KeyedCollection

CA1002 : Microsoft.Design : Change 'List<SomeType>' in 'SomeClass.SomeProtectedOrPublicProperty' to use Collection, ReadOnlyCollection or KeyedCollection

为什么我应该使用 Collection 而不是 List?当我查看 msdn 文档时,它们似乎几乎相等.在阅读了警告的错误帮助后,我发现

Why should I use Collection<T> instead of List<T>? When I look at the msdn documentation, they seem almost equal. After reading the error help for the warning, I found that

System.Collections.Generic.List(T)_是为性能而非继承而设计的通用集合,因此不包含任何虚拟成员.

System.Collections.Generic.List(T)_is a generic collection designed for performance not inheritance and, therefore, does not contain any virtual members.

但这到底是什么意思?我应该怎么做?

But what does this really mean? And what should I be doing instead?

我应该在内部继续使用 List,然后在属性中返回一个 new Collection(someList) 吗?或者我应该开始使用 Collection 而不是 List?

Should I keep using List<T> internally, and then in the properties return a new Collection<T>(someList) instead? Or should I just start using Collection<T> instead of List<T>?

推荐答案

简而言之,泛型列表没有用于添加、删除等的虚拟方法,因为它被设计为快速且不可扩展的.这意味着您不能将这个具体实现换成有用的子类(即使您可以将它子类化,因为它不是密封的).

In short, the generic list does not have virtual methods for Add, Remove etc, as it was designed to be fast, not extensible. This means that you cannot swap this concrete implementation out for a useful subclass (even though you can subclass it as it is not sealed).

因此,通过公开 List 本身,您永远无法扩展您的集合以跟踪添加或删除操作(例如),而不会破坏类的公共契约.

Therefore, by exposing the List itself, you can never extend your collection to track add or remove operations (for example) without breaking the public contract of the class.

通过将你的集合公开为 IList 或类似的东西,你仍然可以使用 List 作为实际的后备存储,但你保留了未来的可扩展性,因为你可以在不改变类的公共契约的情况下稍后换出具体的实现.

By exposing your collection as an IList or some-such, you can still use the List as the actual backing-store, but you retain future extensibility as you can swap out the concerete implementation later without changing the public contract of your class.

这篇关于C#:List&lt;T&gt; 之间的区别和收藏&lt;T&gt;(CA1002,不要公开通用列表)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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