ObservableCollection <t>如何将INotifyPropertyChanged实现为受保护的?</t>

时间:2015-02-19 12:31:42

标签: c# .net interface observablecollection inotifypropertychanged

这是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没有实现接口成员   &#39; System.ComponentModel.INotifyPropertyChanged.PropertyChanged&#39 ;.   &#39; Test.PropertyChanged&#39;无法实现接口成员,因为它   不公开。

这怎么可能?

2 个答案:

答案 0 :(得分:3)

接口本身是显式实现的,具有要覆盖的类的受保护事件

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;
}

答案 1 :(得分:2)

除了受保护的PropertyChanged event之外,ObservableCollection<T>还为INotifyPropertyChanged.PropertyChanged event提供了明确的界面实现,这在您的课程中是缺少的(并且未在{{1的代码段中显示) }})。

您可以阅读explicit interface implementation on MSDN