C# API中模型与它们的接口设计详解

2020-01-05 09:30:12王冬梅

由于这个错误,没有人可以实现带有批量更新支持的INotifyCollectionChanged,除非他们100%确定集合类不会被用在WPF中。

因此,我的建议是不要试图从头开始创建自定义集合类。只需使用ObservableCollection<T>或ReadOnlyObservableCollection<T>作为基类,然后在其上添加所需的任何附加特性。

类型安全的集合变更事件

除了没有人使用的功能之外,INotifyCollectionChanged接口的另一个问题是,它不是类型安全的。如果类型对你来说非常重要,则必须执行(理论上)不安全的转换或编写代码来处理永远不会发生的情况。为了解决这个问题,我建议实现这个接口:


/// <summary>
/// This is a type-safe version of INotifyCollectionChanged
/// </summary>
/// <typeparam name="T"></typeparam>
public interface INotifyCollectionChanged<T>
{
 /// <summary>
 /// This type safe event fires after an item is added to the collection no matter how it is added.
 /// </summary>
 /// <remarks>Triggered by InsertItem and SetItem</remarks>
 event EventHandler<ItemEventArgs<T>> ItemAdded;


 /// <summary>
 /// This type safe event fires after an item is removed from the collection no matter how it is removed.
 /// </summary>
 /// <remarks>Triggered by SetItem, RemoveItem, and ClearItems</remarks>
 event EventHandler<ItemEventArgs<T>> ItemRemoved;
}

这不仅解决了类型安全问题,而且不需要检查NotifyCollectionChangedEventArgs.NewItems的大小。

集合中的属性变更通知

.NET中另一个“缺失的接口”是能够检测集合中某个项目属性何时发生变化。比方说,你有一个OrderCollection类,并且需要在屏幕上显示TotalPrice属性。为了保持这个属性的准确性,你需要知道每个项目的单价何时发生变化。