gpt4 book ai didi

c# - 为什么要将 AsEnumerable() 方法应用于数组?

转载 作者:太空狗 更新时间:2023-10-29 23:00:41 24 4
gpt4 key购买 nike

我正在阅读 C# AsEnumerable :

"The IEnumerable interface is a generic interface. This means it defines a template that types can implement for looping. The AsEnumerable method, a generic method, allows you to cast a specific type to its IEnumerable equivalent"

进一步,代码示例:

using System;
using System.Linq;

class Program
{
static void Main()
{
// Create an array type.
int[] array = new int[2];
array[0] = 5;
array[1] = 6;
// Call AsEnumerable method.
var query = array.AsEnumerable();
foreach (var element in query)
{
Console.WriteLine(element);
}
}
}

听起来我需要将数组转换为 IEnumerable 类型的对象才能使用循环(foreach?)。

但是将 foreach 直接应用于 array 会产生完全相同的结果:

using System;
//using System.Linq;

class Program
{
static void Main()
{
// Create an array type.
int[] array = new int[2];
array[0] = 5;
array[1] = 6;
// Call AsEnumerable method.
//var query = array.AsEnumerable();
foreach (var element in array)
{
Console.WriteLine(element);
}
}
}

所以,整个网页解释AsEnumerable()方法对我来说是无效的。
我错过了什么?

最佳答案

例子不好,感觉应该不好。这是一个更好的示例,尽管有些做作:

如果我在比方说数组类型上定义了一个扩展方法,就像这样:

public static class ArrayExtension {

public static bool Any<T>(this T[] source, Func<T,bool> predicate)
{
Console.WriteLine("Undesirable side behaviour");
SomeResourceIntensiveOperation();

Console.WriteLine("Inefficient implementation");
return source.Where(predicate).Count() != 0;
}

}

我也是

int[] nums = new []{1,2,3,4,5};
nums.Any(n=> n % 2 == 0);

If 将执行并运行我的实现,即使我不需要它。通过做

nums.AsEnumerable().Any(n => n % 2 == 0);

它将调用默认实现。

真正的好处是当您使用IQueryable 实现(例如 LINQ-to-SQL)时,因为,例如,Where for IEnumerable定义为

public static IEnumerable<TSource> Where<TSource>(
this IEnumerable<TSource> source,
Func<TSource, bool> predicate)

但是IQueryable.Where

定义
public static IQueryable<TSource> Where<TSource>(
this IQueryable<TSource> source,
Expression<Func<TSource, bool>> predicate)

当 IQueryable 行为不受欢迎时,可以调用 AsEnumerable() 来强制执行 IEnumerable 行为。

关于c# - 为什么要将 AsEnumerable() 方法应用于数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14171491/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com