C#:列表℃之间的差异; T>并收集和LT; T> (CA1002,不要暴露泛型列表) [英] C#: Difference between List<T> and Collection<T> (CA1002, Do not expose generic lists)

查看:290
本文介绍了C#:列表℃之间的差异; T>并收集和LT; T> (CA1002,不要暴露泛型列表)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试过跑这里来对项目运行code分析,并得到了一些警告说,像这样的:

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

CA1002:Microsoft.Design:更改;在名单,LT的 SOMETYPE >''的 SomeClass.SomeProtectedOrPublicProperty 的使用集合,ReadOnlyCollection还或KeyedCollection

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

我为什么要使用收藏&LT; T&GT; 而不是列表&LT; T&GT; ?当我在看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)的_is泛型集合设计性能不继承的,因此,不包含任何虚拟成员。

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?

我应该继续使用列表&LT; T&GT; 内部,然后在属性返回一个新的集合&LT; T&GT;(someList)呢?或者我应该只是开始使用收藏&LT; T&GT; 而不是列表&LT; T&GT;

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).

因此​​,通过公开目录本身,你永远无法延长您的收藏而不会破坏类的公共合同跟踪添加或删除操作(例如)。

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#:列表℃之间的差异; T&GT;并收集和LT; T&GT; (CA1002,不要暴露泛型列表)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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