English 中文(简体)
Why not expose List(Of String) in the parameters of web service in VB.NET? [duplicate]
原标题:

This question already has answers here:

Closed 10 years ago.

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

最佳回答

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 as IEnumerable<T> or ICollection<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 of List<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 returning IEnumerable<T> or ReadOnlyCollection<T> because I don t want my callers messing with the returned collection.

问题回答

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 a List<T> you are breaking encapsulation by giving client code access to an implementation detail of your class.

A generic list is a .NET construct, however web services are often intended to be interoperable with other frameworks.





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签