C# List Generic Extension Method vs Non-Generic

蹲街弑〆低调 提交于 2019-12-23 08:06:14

问题


This is a simple question (I hope), there are generic and non-generic methods in collection classes like List<T> that have methods such as Where and Where<T>.

Example:

        List<int> numbers = new List<int>()
        {
            1, 2, 3, 4, 5, 6, 7, 8, 9, 10
        };

        IEnumerable<int> evens = numbers.Where((x) =>
        {
            return x % 2 == 0;
        });

        IEnumerable<int> evens2 = numbers.Where<int>((x) =>
        {
            return x % 2 == 0;
        });

Why use one over the other (Generic or Non-Generic)?


回答1:


They're the same method (documentation here). The type parameter portion after the method name (i.e. <int> in this case) is optional when the compiler is able to infer the type automatically and unambiguously from context. In this case, the method is being applied to an object implementing the interface IEnumerable<int> (i.e. the object numbers of type List<int>) from which the compiler can safely infer that the type parameter is int.

Note, also, that Where<T> is actually an extension method on the System.Linq.Enumerable class which can be applied to objects of any class implementing IEnumerable<T> such as List<T>.



来源:https://stackoverflow.com/questions/15152826/c-sharp-list-generic-extension-method-vs-non-generic

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!