[英]C# Override method from Collection<T>
我想在程序每次在列表中添加新项目时通知用户。
我这样做:
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 ,但我不想实现此接口的所有方法...所以我从Collection继承
现在,我对代码有两个疑问:
1º我必须通知用户事件吗? 还是我的代码好?
2º如何调用覆盖方法? 像界面一样?
// IT WORKS!
List<int> _list = new ListDemo<int>();
_list.Insert(0,2);
Console.WriteLine(_list[0]);
这段代码有效,对我来说很奇怪,因为当您调用接口时,必须使用以下方式:
Collection<int> _list = new ListDemo<int>();
3º为什么如果重写方法是InsertItem ,那么当我从实例中调用该方法时,它就是Insert 。
如果您的实现实现了您想要的功能,那就没有问题。 话虽这么说,已经有一个预定义类型ObservableCollection<T>
这是记录在这里 ,这不正是你想要的东西,即提供一种机制,通知如果集合的内容发生变化。
InsertItem
是Collection<T>
的虚拟方法:
protected virtual void InsertItem(
int index,
T item
)
请在这里看看。 因此,当一个类型继承Collection<T>
它可以覆盖此方法,当InsertItem
被调用时,它将被调用。
另一方面, List<T>
不继承Collection<T>
因此没有任何称为InsertItem
方法。
话虽如此,定义您的对象如下:
var listDemo = new ListDemo<int>();
listDemo.InsertItem(0,2);
您将实现所需的目标,因为现在listDemo的类型继承自Collection<int>
并且您已经覆盖了此方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.