使用new隐藏非虚拟成员的替代方法

qua*_*yte 3 c# inheritance

假设我想做这样的事情:

class Foo
{
    public event BarHandler Bar;
    ...
}

class FooList<T> : List<T> where T : Foo
{
    public override void Add(T item)
    {
        item.Bar += Bar_Handler;
        base.Add(item);
    }

    private void Bar_Handler ...

    ...
}
Run Code Online (Sandbox Code Playgroud)

但是,AddList<T>不是虚拟的,所以我不能使用override,我将不得不求助于new代替.然而,这并没有提供多态性,我担心通过FooList简单地引用可能引入的细微错误List,这将导致我的事件处理程序没有被添加.

我目前的具体情况是:我想为ObservableCollection实现的项子类化,INotifyPropertyChanged如果添加/删除它们,则为这些项添加/删除事件处理程序.然后,如果Collection中的任何Item发生更改,我将提供一个Event.

我想为我的特定问题以及潜在的一般问题找到解决方案,因为这是我偶然发现的一些想法,来自java背景.

Tho*_*mar 8

List<T>您可以实现IList<T>接口并保存内部List<T>成员变量,而不是扩展.这样您就不会破坏现有List<T>功能,仍然可以实现相同的界面List<T>.

例:

class FooList<T> : IList<T> where T : Foo
{
    private List<T> m_internalList = new List<T>();

    public void Add(T item)
    {
        item.Bar += Bar_Handler;
        m_internalList.Add(item);
    }

    // other methods
}
Run Code Online (Sandbox Code Playgroud)

  • 组合超过继承,现在我觉得愚蠢的没有看到它.谢谢! (2认同)