T in class? AddRange ICollection?

前端 未结 4 685
感动是毒
感动是毒 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:43

    No, ICollection doesn't have an AddRange method - and even if it did, you'd be trying to dereference null which will throw a NullReferenceException. You haven't specified a collection to add the list to... what exactly are you trying to do?

    You could create (say) a new List - and that has the benefit of already having a constructor which can take an IEnumerable:

    public static ICollection Add(this IEnumerable list)
    {
        return new List(list);            
    }
    

    However, at that point you've really just reimplemented Enumerable.ToList() and given it a different return type...

    If you want to add everything to an existing collection, you might want something like this:

    public static ICollection AddTo(this IEnumerable list,
                                          ICollection collection)
    {
        foreach (T item in list)
        {
            collection.Add(item);
        }
        return collection;
    }
    

提交回复
热议问题