C#泛型列表扩展方法VS非通用 [英] C# List Generic Extension Method vs Non-Generic

查看:307
本文介绍了C#泛型列表扩展方法VS非通用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个简单的问题(我希望),也有集合类通用和非通用的方法,如列表< T> 有方法,如其中,其中,< T>

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>.

例如:

        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)?

推荐答案

他们是同样的方法(文档的此处)。方法名称后的类型参数部分(即< INT> 在这种情况下)是可选的,当编译器能够根据上下文自动和毫不含糊地推断类型。在这种情况下,该方法被应用到实现接口的对象的IEnumerable< INT> (即对象数字类型列表与LT; INT方式> ),从该编译器可以安全地推断该类型参数 INT

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.

请注意,也,谓其中,< T> 实际上是一个的扩展方法的关于 System.Linq.Enumerable 可用于实施任何类的对象类的IEnumerable< T> 列表< T>

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>.

这篇关于C#泛型列表扩展方法VS非通用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆