覆盖List 的Add()
我不能重载List的Add方法吗?
class ListDemo:List { public override T Add(T value) { return base.Add(value); } }
我收到以下错误:
1)类型参数“T”与外部类型“CollectionsExample.ListDemo”中的类型参数同名
2)’CollectionsExample.ListDemo.Add(T)’:找不到合适的方法来覆盖
您应该封装List
并实现IList
,而不是从List
inheritance子类。 这使得处理“覆盖”Add的行为变得容易:
public class ListDemo : IList { private List list = new List (); // Internal list public void Add(T item) { // Do your pre-add logic here list.Add(item); // add to the internal list // Do your post-add logic here } // Implement all IList methods, just passing through to list, such as: }
List
不应该是您的公共API的一部分 – 它应该是一个实现细节。
正确的代码是:
class ListDemo:List { public new void Add(T value) { base.Add(value); } }
类声明和方法都不需要类型参数。 在这种情况下,它是通用的类声明; 因此,当您尝试将Add方法声明为采用名为T的generics类型参数时,编译器将抱怨您尝试使用具有相同名称的2个类型参数。
编辑 :修复了代码示例。 由于Add不是虚拟的,因此不能使用override关键字覆盖它(因此原始样本实际上不会编译)。 您仍然可以使用new声明它,但这可能会导致Add方法的含义不同。 我会强烈考虑实施IList
这对我有用(根据Sam Harwell的评论):
public class ListDemo : Collection { protected override void InsertItem(int index, T item) { // Your add condition ... if (!this.Any(x => ...)) base.InsertItem(index, item); } }
如果你想要一个你想要覆盖你的添加/插入或索引器的集合,那么你可以创建自己的集合,它将inheritance自:
Collection
并覆盖以下方法:
InsertItem(); SetItem();
第一个由Add()和Insert()调用,而第二个由this []调用
List
添加无法覆盖,因为集合是针对性能而进行的,因此有意删除了覆盖的可能性
从List
派生几乎总是毫无意义。 有关完整纲要,请参阅我对此其他问题的回答:
如何在.NET 2.0中创建自定义集合
如果这个类能够满足您的需求,那么从List中派生并非毫无意义。 而你想要做的就是添加一些方法,比如FindCar(Car dodge).