Why does IEnumerable.ToList() return List instead of IList?

前端 未结 10 1749
暖寄归人
暖寄归人 2020-12-29 02:23

The extension method ToList() returns a List. Following the same pattern, ToDictionary() returns a Dictionary<

10条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-29 02:45

    Because List actually implements a range of interfaces, not just IList:

    public class List : IList, ICollection, IList, ICollection, IReadOnlyList, IReadOnlyCollection, IEnumerable, IEnumerable{
    
    }
    

    Each of those interfaces define a range of features which the List must conform. Picking one particular one, would render bulk of the implementation unusable.

    If you do want to return IList, nothing stops you from having your own simple wrapper:

    public static IList ToIList(this IEnumerable source)
    {
        if (source == null) throw new ArgumentNullException(source);
        return source.ToList();
    }
    

提交回复
热议问题