T in class? AddRange ICollection?

前端 未结 4 686
感动是毒
感动是毒 2021-01-12 12:07

I try to do static class, add to icollection but i got some issues i cant seem to overcome. that is how i get so i can pass a ICollection in the method? cause T is that say

4条回答
  •  星月不相逢
    2021-01-12 12:28

    The other ways seem to assume that your ICollection is empty and/or your ICollection is a type of List. However, if you want AddRange, then you can Extend the ICollection class as follows:

    public static void AddRange(this ICollection ic, IEnumerable ie)
    {
        foreach (T obj in ie)
        {
            ic.Add(obj);
        }
    }
    

    Note, however, that since List impliments ICollection, this may cause ambiguity when dealing directly with List objects (though I haven't tested yet if the compiler will be able to resolve it--my gut reaction is that it should, though, since AddRange is a member of List and the compiler will go through member functions first before looking at extensions, but if I'm wrong I'm sure someone will correct me).

提交回复
热议问题