锁定/解锁的ObservableCollection< T>

锁定/解锁的ObservableCollection< T>

问题描述:

我有一个要求,允许或prevent修改的的ObservableCollection< T> (或至少是一种实现 INotifyCollectionChanged 为WPF绑定)以及它所包含的对象根据业务规则。

I have a requirement to allow or prevent modification to an ObservableCollection<T> (or at least a type that implements INotifyCollectionChanged for WPF binding) as well as the objects it contains based on a business rule.

我可以解决的preventing修改问题包含的对象,但我不知道如何处理preventing改变集合本身。一种选择是将订阅 Col​​lectionChanged 事件,并撤销更改它们发生后,但就是不优雅和再presents一个令人困惑的合同到客户端。

I can solve the issue of preventing modification to contained objects, but am not sure how to approach preventing change to the collection itself. One option would be to subscribe to the CollectionChanged event and undo changes after they happen, but that is not elegant and represents a confusing contract to the client.

还有什么其他的方法有哪些?

What other approaches are there?

您可以宣布自己的类实现ICollection的(朋友)接口,并具有潜在的集合是该类的成员。你不会希望继承因为当时有人可能会简单地把对象引用的基类,你失去了你的保护。

You could declare your own class that implements ICollection (and friends) interfaces and have the underlying collection be a member of that class. You wouldn't want to inherit because then someone might simply cast object reference to the base class and you've lost your protection.

在正常情况下,委托的所有更新基础类,直到集合变为锁定。当它被锁定,开始扔转发调用下面的说法来代替。而所有的读操作总是委托。

Under normal conditions, delegate all updates to the underlying class until the collection becomes locked. When it's locked, start throwing assertions instead of forwarding the calls below. And all read operations are always delegated.

这将基本上是一个装饰图案