ObservableCollection<T> 如何实现受保护的 INotifyPropertyChanged?

How does ObservableCollection<T> implement INotifyPropertyChanged as protected?

这是INotifyPropertyChanged

的定义
public interface INotifyPropertyChanged
{
    event PropertyChangedEventHandler PropertyChanged;
}

ObservableCollection<T> 实现了这个...

public class ObservableCollection<T> : Collection<T>, INotifyCollectionChanged, INotifyPropertyChanged
{
    protected virtual event PropertyChangedEventHandler PropertyChanged;
}

当我测试这个时...

public class Test : INotifyPropertyChanged
{
    protected virtual event PropertyChangedEventHandler PropertyChanged;
}

我收到以下错误:

Test does not implement interface member 'System.ComponentModel.INotifyPropertyChanged.PropertyChanged'. 'Test.PropertyChanged' cannot implement an interface member because it is not public.

这怎么可能?

除了受保护的 PropertyChanged event, ObservableCollection<T> provides an explicit interface implementation for the INotifyPropertyChanged.PropertyChanged event,您的 class 中缺少它(并且未显示在 ObservableCollection<T> 的代码片段中)。

您可以阅读 explicit interface implementation on MSDN

接口本身是显式实现的,类 有一个受保护的事件可以覆盖

public class Test : INotifyPropertyChanged
{
   // explicit interface implementation
    event PropertyChangedEventHandler INotifyPropertyChanged.PropertyChanged
    {
        add
        {
            PropertyChanged += value;
        }
        remove
        {
            PropertyChanged -= value;
        }
    }

    // protected virtual (for derived classes to override)   
    protected virtual event PropertyChangedEventHandler PropertyChanged;
}