来自Collection <t>的C#覆盖方法

时间:2017-06-06 10:35:48

标签: c# inheritance interface

每次程序在列表中添加新项目时,我都想通知用户。

我这样做了:

public class ListDemo<T> : Collection<T>
{
    protected override void InsertItem(int index, T item)
    {
        Console.WriteLine("YOU HAVE INSERTED AN ITEM");
        base.InsertItem(index, item);
    }
}

我可以从界面 IList 继承 ListDemo ,但我不想实现此界面的所有方法......所以我继承自集合

现在我对我的代码有两个问题:

我是否必须通过活动通知用户?或者我的代码很好?

如何调用覆盖方法?像界面一样?

         // IT WORKS!
         List<int> _list = new ListDemo<int>();
        _list.Insert(0,2);
        Console.WriteLine(_list[0]);

此代码有效,对我来说非常奇怪,因为当你调用某个界面时,你必须使用这种方式:

        Collection<int> _list = new ListDemo<int>();

为什么如果覆盖方法是 InsertItem ,那么当我从我的实例调用方法时,这只是插入

2 个答案:

答案 0 :(得分:2)

如果你的实现做了你想要的,没有问题。话虽如此,已经有一个预定义的类型ObservableCollection<T>,其中记录了here,它完全符合您的要求,即如果集合的内容发生变化,则提供通知机制。

答案 1 :(得分:1)

InsertItemCollection<T>虚拟方法:

protected virtual void InsertItem(
    int index,
    T item
)

请查看here。因此,当类型继承Collection<T>时,它可以覆盖此方法,并且当InsertItem被调用时,它将被调用。

另一方面,List<T>并不会继承Collection<T>,因此没有任何名为InsertItem的方法。

话虽如此,将对象定义如下:

var listDemo = new ListDemo<int>();
listDemo.InsertItem(0,2);

你会实现你想要的,因为现在listDemo的类型继承自Collection<int>,你已经覆盖了这个方法。