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

时间:2015-01-06 08:23:28

标签: 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 ...

    ...
}

Add中的List<T>不是虚拟的,因此我无法使用override,我将不得不诉诸new。然而,这并没有提供多态性,我担心通过引用FooList简单List可能引入的细微错误,这会导致我的事件处理程序没有被添加。

我目前的具体情况是:我希望为实现ObservableCollection的项创建INotifyPropertyChanged子类,并在添加/删除这些项时添加/删除事件处理程序。然后,如果Collection中的任何Item发生更改,我会提供一个Event。

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

2 个答案:

答案 0 :(得分:8)

您可以实现IList<T>接口并保留内部List<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
}

答案 1 :(得分:3)

List<T>无意继承,因此Add方法不是虚拟的,但Collection<T>是。Collection<T>。您可以继承InsertItem并覆盖internal class MyCollection<T> : Collection<T> where T : Foo { protected override void InsertItem(int index, T item) { item.Bar += Bar_Handler; base.InsertItem(index, item); } } 方法。

Collection<T>

相关:Why not inherit from List<T>?

FWIW ObservableCollection<T>类本身继承{{1}}。