为什么ObservableCollection没有RemoveAll方法? [英] Why ObservableCollection does not have a RemoveAll method?
问题描述
为什么 ObservableCollection
没有像 List
这样的 RemoveAll
方法?
Why ObservableCollection
doesn't has the RemoveAll
method like a List
?
我已经实现了扩展方法,以向 ObservableCollection
提供此功能,但是我想了解是否有不提供此功能的特定原因.
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.
由于集合更改,它是否可能以某种方式影响数据绑定?此帖子确实指定了一些在使用 ObservableCollections
时可能出错的地方,但没有解决这个问题.
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.
推荐答案
它确实具有 Clear()
方法,该方法删除了所有可以代替使用的项.
It does have a Clear()
method that removes all items that you can use instead.
如果我不得不猜测为什么他们使用 Clear
而不是 RemoveAll
,我认为这是因为 RemoveAll
带有建议您从集合中删除项目,而 Clear
告诉您这些项目只是被清除.
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.
这与引发的 CollectionChanged
通知的类型有所不同. Clear()
引发一个 NotifyCollectionChangedAction.Reset
事件,并且不包括该事件中已删除的项目,而 Remove
引发一个 NotifyCollectionChangedAction.已删除
事件,并将已删除项目传递给该事件.
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.
您不能引发包含多个项目的 CollectionChanged
事件,因此引发删除所有项目的NotifyCollectionChangedAction.Removed
事件将引发异常.另一种选择是为每个被删除的项目引发一个 CollectionChanged
事件,这可能会降低性能.而且,当用户期望在删除项目时发生 Removed
事件时,仅引发 NotifyCollectionChangedAction.Reset
事件会引起一些混乱.
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.
所以我猜他们决定只使用 .Clear()
而不是 .RemoveAll()
,因为该名称更好地描述了实际发生在场景.
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.
这篇关于为什么ObservableCollection没有RemoveAll方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!