List.AddRange是否调用List.Add?

Sup*_*est 5 .net c# list

我有一个从List派生的自定义类,其中Add方法只在满足某个条件时才会添加.

我是否还需要覆盖*AddRange,或者AddRange是否只是在给定范围的每个元素上调用Add?

*:是的,new隐藏在C#的背景下不重写.

Céd*_*non 9

如果要创建自定义集合.不要从它派生List<T>Collection<T>还是直接实现IList<T>ICollection<T>.实际上,该类中的Add方法List<T>不是虚拟的.

注意:List<T>.AddRange用途Array.Copy.

UPDATE

继承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.