Why ObservableCollection does not have a RemoveAll

2020-08-13 02:08发布

问题:

Why ObservableCollection doesn't has the RemoveAll method like a List?

I have implemented an extension method to provide this functionality to the ObservableCollection, but I would like to understand if there is a specific reason for not providing this functionality.

Would it possibly effect Data Binding in some way due to Collection change? This post does specify a few things that could go wrong while using ObservableCollections, but does not address this question.

回答1:

It does have a Clear() method that removes all items that you can use instead.

If I had to hazard a guess as to why they used Clear instead of RemoveAll, I think it would be because RemoveAll carries the suggestion that you are removing items from the collection, while Clear tells you the items are simply being cleared.

This makes a difference in the type of CollectionChanged notification that gets raised. Clear() raises a NotifyCollectionChangedAction.Reset event and does not include the removed items in the event, while Remove raises a NotifyCollectionChangedAction.Removed event, and passes the removed item to the event.

You cannot raise a CollectionChanged event with multiple items, so raising a NotifyCollectionChangedAction.Removed event with all the items removed would throw an exception. The alternative would be to raise a CollectionChanged event for every item that got removed, which can be quite bad for performance. And simply raising a NotifyCollectionChangedAction.Reset event would cause some confusion when users are expecting a Removed event to occur when they are removing items.

So I am guessing they decided to simply use .Clear() instead of .RemoveAll() because the name is a better description of what is actually happening behind the scenes.



回答2:

You might as well ask why it does not implement Reverse or any other method. There simply is no reason to implement more than the most common and absolutely necessary methods. Everything beside Add and Remove is just convenience. (RemoveAll is not even part of the common interfaces that lists implement, and they do have a lot of methods already)