List.AddRange list calls List.Add?

I have a custom class derived from List with the Add method, which is added only if a certain condition is met.

Do I also need to override * AddRange, or does AddRange just call Add on each element of a given range?

*: Yes, it newhides and is not redefined in the context of C #.

+5
source share
3 answers

If you want to create a custom collection. Do not derive it from List<T>, but from Collection<T>or directly implement IList<T>or ICollection<T>. In fact, a method Addin a class is List<T>not virtual.

Note: List<T>.AddRangeuses 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);
    }
}

string string .

+9

, . .

, IList<T>. - Collection<T>. Collection<T> IList<T> protected virtual:

InsertItem
SetItem
RemoveItem
ClearItems

, , , , InsertItem SetItem.

class MyCollection:Collection<T>
{
    private void ValidateItem(T item)
    {
       if(item is invalid)
         throw new ArgumentException("Item is invalid");
    }

    protected override InsertItem(int index, T item)
    {
        ValidateItem(item);
        base.InsertItem(index, item);
    }

    protected override SetItem(int index, T item)
    {
        ValidateItem(item);
        base.SetItem(index, item);
    }
}
+4

, , List<T>, , .

AddIfValid(T value) AddRangeIfValid(IEnumerable<T>) , , , , .

:

public static void AddIfValid(this List<T> list, T value)
{
    if (/* check if value is valid here */)
        list.Add(value);
}

Once you have identified the extension, use it as follows:

myList.AddIfValid(myValue);
+2
source