这是一个简单的问题(我希望),集合类中有泛型和非泛型方法,如List<T>
具有类似 Where
的方法和 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;
});
为什么要使用一个而不是另一个(通用或非通用)?
最佳答案
它们是相同的方法(文档 here )。当编译器能够从上下文自动且明确地推断类型时,方法名称后的类型参数部分(即本例中的 <int>
)是可选的。在这种情况下,该方法将应用于实现接口(interface) IEnumerable<int>
的对象。 (即 numbers
类型的对象 List<int>
),编译器可以从中安全地推断出类型参数是 int
.
另请注意,Where<T>
实际上是 System.Linq.Enumerable
上的扩展方法可以应用于任何实现 IEnumerable<T>
的类的对象的类例如List<T>
.
关于C# 列表泛型扩展方法与非泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15152826/