【问题标题】:How does ObservableCollection<T> implement INotifyPropertyChanged as protected?ObservableCollection<T> 如何将 INotifyPropertyChanged 实现为受保护?
【发布时间】:2015-02-19 12:31:41
【问题描述】:

这是INotifyPropertyChanged的定义

public interface INotifyPropertyChanged
{
    event PropertyChangedEventHandler PropertyChanged;
}

ObservableCollection&lt;T&gt; 实现了这个...

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

当我测试这个时...

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

我收到以下错误:

测试没有实现接口成员 'System.ComponentModel.INotifyPropertyChanged.PropertyChanged'。 “Test.PropertyChanged”无法实现接口成员,因为它 不公开。

这怎么可能?

【问题讨论】:

  • 这是一个错误的问题,它没有受到保护,它被实现为私有......!
  • @JenishRabadiya 你能详细说明一下吗?
  • PropertyChanged 在 ObservableCollection 中是私有的,只需相应地更新标题和问题。 protected 是不可能的。
  • @JenishRabadiya 问题的关键在于确定 ObservableCollection 如何实现 INotifyPropertyChanged。当我看到受保护的虚拟成员时,我很困惑,但是如果您阅读了接受的答案 - 这就是我想要的。

标签: c# .net interface observablecollection inotifypropertychanged


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    除了受保护的PropertyChanged eventObservableCollection&lt;T&gt; 还为您的类中缺少的INotifyPropertyChanged.PropertyChanged event 提供了显式接口实现(并且未在您的代码中显示来自ObservableCollection&lt;T&gt; 的sn-p)。

    你可以阅读explicit interface implementation on MSDN

    【讨论】:

      猜你喜欢
      • 2015-09-29
      • 1970-01-01
      • 2012-04-05
      • 1970-01-01
      • 2012-05-04
      • 1970-01-01
      • 1970-01-01
      • 2019-08-18
      • 1970-01-01
      相关资源
      最近更新 更多