[英]Can't compile LINQ extension methods on classes that derive from a class implementing IEnumerable<out T>
[英]How can Array use LINQ extension methods since Array does not implent IEnumerable<T> interface
这是我的程序:
static void Main(string[] args)
{
int[] myArr = new int[] { 4,6,2,1};
//call Where() linq method
var myEvenNumbers = myArr.Where(n => n % 2 == 0 );
Console.Read();
}
但是当我在Enumerable类中查看Where()扩展方法的定义时
public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate);
public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source, Func<TSource, int, bool> predicate);
源的类型为IEnumerable<T>
。
我的问题是:数组类未实现IEnumerable<T>
但是我们如何仍可以在数组上使用Where()扩展方法?
数组确实实现了IEnumerable以及ICollection(及其泛型)以及许多其他对象
foreach (var type in (new int[3]).GetType().GetInterfaces())
Console.WriteLine(type);
产生
Array没有实现IEnumerable<T>
,如果您尝试使用需要IEnumerable<T>
的变量以及实际键入为Array
的变量,则会看到该变量。 特定类型的阵列类型(如int[]
如在你的例子) 并实现IEnumerable<T>
与其它一般类型一起。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.