System.Collections Vs System.Collections.ObjectModel
There seem to be certain collection classes in System.Collections.ObjectModel as well. What is the difference between the collections under these two namespaces and in which scenario should we use System.Collections.Ob开发者_如何转开发jectModel?
From MSDN:
The System.Collections.ObjectModel namespace contains classes that can be used as collections in the object model of a reusable library. Use these classes when properties or methods return collections.
See also The reason why Collection, ReadOnlyCollection, and KeyedCollection were moved to System.Collections.ObjectModel namespace
System.Collections.ObjectModel
classes are useful for exposing your collections to the outside world. (By outside world I mean code that does not version with your code.)
So use generic collection classes in your code, but wrap it in a Collection<T>
, ReadOnlyCollection<T>
, or ObservableCollection<T>
when you want to expose it to the outside world.
To wrap a collection as a keyed collection, the KeyedCollection
can be used as a base class for a helper.
One obvious difference is that the System.Collections.ObjectModel
namespace contains generic
readonly collections (i.e. without the Add, Remove and Clear methods etc).
精彩评论