.net - Which list/collection type is best to use in a WCF data contract?

问题描述:

When defining a WCF data contract, which type should one use for collections/lists?

Should it be ICollection<T>,

IList<T>, T[] or...?

Should I use interface types or the concrete types?

What trade offs are there to consider?

网友答案:

note: I'm answering this from the client's perspective - i.e. the /collectionType:<type> switch on svcutil.exe (also available in the IDE).

Personally, I tend to keep it simple and use List<T>. If you are going to do lots of data binding, BindingList<T> might be an option, but for object properties it is usually overkill. Arrays make life very hard... avoid them ;-p

Note that with .NET 3.5 the features available to each collection type blur, thanks to the extension methods on Enumerable.

Normally, Collection<T> is useful when you think you might want to subclass the collection to use the virtual extension points. This isn't really an option with WCF.

As already stated, using IList<T> etc isn't an option unless you are using assembly sharing, since the generated class won't be able to create the collection.

网友答案:

You can not use interface type in datacontract because the serializer won't work with interface type properties.

You can use concrete type e.g. MyClass[] or List

网友答案:

Aside from the fact that you can't use interface types, it doesn't really matter which of the collection types you use. The client of your service will never see them.

Remember that web services provide a descriptionj of the service to the client in terms of WSDL or mex. In the case of WSDL, the client will receive an XML Schema describing the messages to be sent and received. In the case of a collection, the client will simply see an element with a maxOccurs="unbounded" instead of one with maxOccurs="1". The client may interpret this as an array, or list, or whatever. No matter which collection you return from your service, the client will see maxOccurs="unbounded" and interpret it as it likes.

The exception would be returning a dictionary of some kind, and I don't know how that works.