【问题标题】:How can I implement an interface member in protected?如何在受保护的情况下实现接口成员?
【发布时间】:2010-03-19 09:58:09
【问题描述】:

当我在 VS 2008 中看到 ReadOnlyObservableCollection 的元数据时,我感到非常惊讶......

public class ReadOnlyObservableCollection<T> : ReadOnlyCollection<T>, INotifyCollectionChanged, INotifyPropertyChanged
{
    // Summary:
    //     Initializes a new instance of the System.Collections.ObjectModel.ReadOnlyObservableCollection<T>
    //     class that serves as a wrapper for the specified System.Collections.ObjectModel.ObservableCollection<T>.
    //
    // Parameters:
    //   list:
    //     The collection to wrap.
    public ReadOnlyObservableCollection(ObservableCollection<T> list);

    // Summary:
    //     Occurs when an item is added or removed.
    protected virtual event NotifyCollectionChangedEventHandler CollectionChanged;
    //
    // Summary:
    //     Occurs when a property value changes.
    protected virtual event PropertyChangedEventHandler PropertyChanged;

    // Summary:
    //     Raises the System.Collections.ObjectModel.ReadOnlyObservableCollection<T>.CollectionChanged
    //     event.
    //
    // Parameters:
    //   args:
    //     The event data.
    protected virtual void OnCollectionChanged(NotifyCollectionChangedEventArgs args);
    //
    // Summary:
    //     Raises the System.Collections.ObjectModel.ReadOnlyObservableCollection<T>.PropertyChanged
    //     event.
    //
    // Parameters:
    //   args:
    //     The event data.
    protected virtual void OnPropertyChanged(PropertyChangedEventArgs args);
}

如您所见,INotifyCollectionChanged 的​​成员 CollectionChanged 是在 protected... 中实现的,而我无法在自己的类中这样做。

.NET 框架不应该编译!

有人解释过这个谜吗?

【问题讨论】:

    标签: c# .net


    【解决方案1】:

    如果您仔细检查 ReadOnlyObservableCollection,您会发现它显式 实现了 INotifyPropertyChanged。换句话说,受保护的事件处理程序并不是接口的真正实现——INotifyCollectionChanged.CollectionChanged 是。

    【讨论】:

      【解决方案2】:

      我已经检查过 Reflector,这是我发现的:

      protected event NotifyCollectionChangedEventHandler CollectionChanged;
      protected event PropertyChangedEventHandler PropertyChanged;
      event NotifyCollectionChangedEventHandler INotifyCollectionChanged.CollectionChanged;
      event PropertyChangedEventHandler INotifyPropertyChanged.PropertyChanged;
      

      所以事件实际上已经实现了。

      【讨论】:

        【解决方案3】:

        我同意 Mark Seemann 的 回答,并查看 this question 一些有用的东西可以在答案中找到。这一切都归功于显式接口实现。尝试在你的类型中显式地实现 INotifyPropertyChanged(或任何其他接口),然后通过对象浏览器打开它,你会看到它显示接口成员甚至是私有的。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-06-12
          • 1970-01-01
          • 1970-01-01
          • 2010-11-17
          • 2020-11-21
          • 1970-01-01
          • 1970-01-01
          • 2014-11-14
          相关资源
          最近更新 更多