代码之家  ›  专栏  ›  技术社区  ›  Nicolas Dorier

如何在Protected中实现接口成员?

  •  2
  • Nicolas Dorier  · 技术社区  · 16 年前

    当我看到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);
    }
    

    如您所见,CollectionChanged是在Protected中实现的,它是InotifyCollectionChanged的成员…在我自己的班级里我不能这样做。

    .NET框架不应编译!

    有人能解释这个谜吗?

    3 回复  |  直到 16 年前
        1
  •  3
  •   Mark Seemann    16 年前

    如果仔细检查readOnlyobservableCollection,就会发现它 明确地 实现InotifyPropertiesChanged。换句话说,受保护的事件处理程序不是接口的真正实现- INotifyCollectionChanged.CollectionChanged 是。

        2
  •  1
  •   Andrew Bezzub    16 年前

    我检查过反射镜,我发现:

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

    所以事件实际上是被实现的。

        3
  •  1
  •   Community Mohan Dere    9 年前

    我同意 马克·西曼 回答并看一下 this question 答案中可以找到一些有用的东西。这一切都是由于显式接口实现。尝试实施 InotifyProperty已更改 (或任何其他接口)在您的类型中明确地显示出来,然后通过对象浏览器打开它,您将看到这显示接口memeber,即使是私有的。