如何在受保护的环境中实现接口成员?

时间:2010-03-19 09:58:10

标签: c# .net

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

正如你所看到的,CollectionChanged是INotifyCollectionChanged的一个成员,是在受保护的......中实现的。我不能在我自己的班级中这样做。

.NET框架不应该编译!

有人对这个谜团有解释吗?

3 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:1)

我已经使用Reflector进行了检查,这是我发现的:

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

事实上,事件已经实施。

答案 2 :(得分:1)

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