我有一个从List派生的自定义类,其中Add方法只在满足某个条件时才会添加.
我是否还需要覆盖*AddRange,或者AddRange是否只是在给定范围的每个元素上调用Add?
*:是的,new
是隐藏在C#的背景下不重写.
如果要创建自定义集合.不要从它派生List<T>
但Collection<T>
还是直接实现IList<T>
或ICollection<T>
.实际上,该类中的Add
方法List<T>
不是虚拟的.
注意:List<T>.AddRange
用途Array.Copy
.
继承Collection时,您只需要覆盖2个方法!
public class MyCollection : Collection<string>
{
private bool IsValidItem(string item)
{
return; // Your condition : true if valid; false, otherwise.
}
// This method will be called when you call MyCollection.Add or MyCollection.Insert
protected override void InsertItem(int index, string item)
{
if(IsValidItem(item))
base.InsertItem(index, item);
}
// This method will be called when you call MyCollection[index] = newItem
protected override void SetItem(int index, string item)
{
if(IsValidItem(item))
base.SetItem(index, item);
}
}
Run Code Online (Sandbox Code Playgroud)
如果要验证的项目未在上面的代码中以正确的类型string
替换string
.
归档时间: |
|
查看次数: |
1404 次 |
最近记录: |