为什么不在 VB.NET 中的 Web 服务参数中公开 List(Of String)?
FxCop 在一条规则中表示,通用列表不应向外界公开。
但我不明白为什么以及通用列表的替代品是什么?
参考:http://msdn.microsoft.com/ en-in/library/ms182142%28en-us%29.aspx
Possible Duplicate:
C#: Difference between List<T> and Collection<T> (CA1002, Do not expose generic lists)
The FxCop says in a rule that generic List should not be exposed to the outside world.
But I do not understand why and what is the replacement for the generice List?
Reference : http://msdn.microsoft.com/en-in/library/ms182142%28en-us%29.aspx
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
原因是使用具体的
List
意味着实现细节,并且您应该公开一些更抽象的东西,例如IEnumerable
code> 或ICollection
,仅表示您想要公开的功能(例如可枚举、可变和/或可索引)。这使您可以灵活地稍后更改实现。在实践中,通常通过返回
IList
而不是List
来解决此警告,但其想法是提示您思考“什么功能我实际上需要来保证我的呼叫者吗?”例如,也许我应该返回IEnumerable
或ReadOnlyCollection
因为我不希望我的调用者弄乱返回的集合。The reason is that the use of a concrete
List<T>
is meant to be an implementation detail, and you're meant to expose something more abstract, such asIEnumerable<T>
orICollection<T>
, that represents only the functionality you want to expose (such as being enumerable, mutable and/or indexable). This gives you flexibility to change the implementation later on.In practice, this warning is often resolved by returning
IList<T>
instead ofList<T>
, but the idea is to prompt you to think about "what functionality do I actually need to guarantee my callers?" E.g. maybe I should be returningIEnumerable<T>
orReadOnlyCollection<T>
because I don't want my callers messing with the returned collection.始终公开对象层次结构中适合您的场景的最低基类/接口。例如,如果此属性的使用者仅要对其进行迭代,请使用
IEnumerable(Of T)
。通过公开List
,您将通过允许客户端代码访问您的类的实现细节来破坏封装。Always expose the lowest base class/interface in the object hierarchy that will be suitable for your scenario. For example if consumers of this property are going to only iterate over it use
IEnumerable(Of T)
. By exposing aList<T>
you are breaking encapsulation by giving client code access to an implementation detail of your class.通用列表是 .NET 构造,但是 Web 服务通常旨在与其他框架进行互操作。
A generic list is a .NET construct, however web services are often intended to be interoperable with other frameworks.