简体   繁体   English

集合中的C#覆盖方法<T>

[英]C# Override method from Collection<T>

I would like to notify to the user each time that the program add a new Item in a List. 我想在程序每次在列表中添加新项目时通知用户。

I did this: 我这样做:

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);
    }
}

I could inherit ListDemo from the interface IList , but I don't want to implement all the methods of this interface... So I inherited from Collection 我可以从IList接口继承ListDemo ,但我不想实现此接口的所有方法...所以我从Collection继承

Now I have two questions about my code: 现在,我对代码有两个疑问:

Do I have to notify to the user with an event? 我必须通知用户事件吗? Or my code is good? 还是我的代码好?

How Can I call to the override method? 如何调用覆盖方法? Like an Interface? 像界面一样?

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

This code works, and it is very strange for me, because when you call to an interface you must use this way: 这段代码有效,对我来说很奇怪,因为当您调用接口时,必须使用以下方式:

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

Why if the override method is InsertItem , then when I call to the method from my instance this is simply Insert . 为什么如果重写方法是InsertItem ,那么当我从实例中调用该方法时,它就是Insert

If you implementation does what you want, there is no problem. 如果您的实现实现了您想要的功能,那就没有问题。 That being said, there is already a predefined type ObservableCollection<T> , which is documented here , which does exactly what you want, namely providing a mechanism for notifications if the content of the collections changes. 话虽这么说,已经有一个预定义类型ObservableCollection<T>这是记录在这里 ,这不正是你想要的东西,即提供一种机制,通知如果集合的内容发生变化。

The InsertItem is a virtual method of Collection<T> : InsertItemCollection<T>虚拟方法:

protected virtual void InsertItem(
    int index,
    T item
)

Please have a look here . 在这里看看。 So when a type inherits a Collection<T> then it can override this method and when InsertItem is called the overriden one it would be called. 因此,当一个类型继承Collection<T>它可以覆盖此方法,当InsertItem被调用时,它将被调用。

On the other hand List<T> doesn't not inherits Collection<T> so there isn't any method called InsertItem . 另一方面, List<T>不继承Collection<T>因此没有任何称为InsertItem方法。

That being said, defining you object as below: 话虽如此,定义您的对象如下:

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

you would achieve that you want, because now the type of listDemo inherits from Collection<int> and you have overriden this method. 您将实现所需的目标,因为现在listDemo的类型继承自Collection<int>并且您已经覆盖了此方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM