How to provide a readonly Collection that implements INotifyCollectionChanged
Is there a efficient way to provide an Enumarable<SomeType>
or a collection that implements INotifyCollectionChanged but that can only be changed from the inside of the providing class.
The following example shows what I mean, but has the disadvantage that the caller can cast the IEnumerable<SomeType>
back and then manipulate my internal collection, what I really would dislike:
public class DemoClass{
ObservableCollection<SomeType> m_collection=
new ObservableCollection<SomeType>();
public IEnumerable<SomeType> SomeTypeInstances{
get{return m_collection;}
}
private void AMethod(){
// Here I can work with m_collection
}
}
Is there an easy way, perhaps with the ObservableCollection, or is it necessary to write a wrap开发者_开发技巧per that implements IEnumerable<SomeType>
and INotifyCollectionChanged
and then forwarding collectionchanged-evnets to the destination?
Use ReadOnlyObservableCollection<T>
.
if you return the internal collection then they can always mess with your data. you could just give the user a ReadOnlyCollection<T>
that is a clone of the internal data. That way, they can get to the data and your data isn't at risk of being corrupted.
精彩评论