在执行IEnumerable<T>方法之前,方法returns如何导致C#?
How does before executing the IEnumerable<T> method, method returns result in C#?
在显示 MyList 中大于 2 的数字的代码块下方。
using System;
using System.Collections.Generic;
namespace CSharpBasics
{
internal class Program
{
private static List<int> MyList = new List<int>();
private static void Main(string[] args)
{
MyList.Add(1);
MyList.Add(2);
MyList.Add(3);
MyList.Add(4);
var test = FilterWithYield();
foreach (int i in test)
{
Console.WriteLine(i);
}
Console.ReadLine();
}
private static IEnumerable<int> FilterWithYield()
{
foreach (int i in MyList)
{
if (i > 2)
{
yield return i;
}
}
}
}
}
现在当我们将断点设置到第 foreach (int i in test)
行时,在执行 foreach
循环 之前, test
变量将具有来自 FilterWithYield()
的结果。这怎么可能?我的理解是,在迭代开始之前,IEnumerable 方法从未执行过。
我遗漏了什么吗?
谢谢。
查看警告 - Expanding the Result View will enumerate the IEnumerable…
通过查看结果视图,您正在枚举值。
test
是一个 enumerable - 本质上是一个枚举器提供者;当它被枚举时,enumerator 被迭代获取。现在;枚举数和可枚举数通常是不同的,但可枚举数 (test
) 仍然是 something,并且 something 仍然有一些状态IDE 可以探测。 IDE 可以 检测 可枚举,并 为您迭代它们 以显示内容。在某些情况下(序列不可重复),这实际上可能非常不方便。因此,IDE 在您单击它之前确实警告过您 - 请参阅 "Expanding the Results View will enumerate the IEnumerable"。
在显示 MyList 中大于 2 的数字的代码块下方。
using System;
using System.Collections.Generic;
namespace CSharpBasics
{
internal class Program
{
private static List<int> MyList = new List<int>();
private static void Main(string[] args)
{
MyList.Add(1);
MyList.Add(2);
MyList.Add(3);
MyList.Add(4);
var test = FilterWithYield();
foreach (int i in test)
{
Console.WriteLine(i);
}
Console.ReadLine();
}
private static IEnumerable<int> FilterWithYield()
{
foreach (int i in MyList)
{
if (i > 2)
{
yield return i;
}
}
}
}
}
现在当我们将断点设置到第 foreach (int i in test)
行时,在执行 foreach
循环 之前, test
变量将具有来自 FilterWithYield()
的结果。这怎么可能?我的理解是,在迭代开始之前,IEnumerable 方法从未执行过。
我遗漏了什么吗?
谢谢。
查看警告 - Expanding the Result View will enumerate the IEnumerable…
通过查看结果视图,您正在枚举值。
test
是一个 enumerable - 本质上是一个枚举器提供者;当它被枚举时,enumerator 被迭代获取。现在;枚举数和可枚举数通常是不同的,但可枚举数 (test
) 仍然是 something,并且 something 仍然有一些状态IDE 可以探测。 IDE 可以 检测 可枚举,并 为您迭代它们 以显示内容。在某些情况下(序列不可重复),这实际上可能非常不方便。因此,IDE 在您单击它之前确实警告过您 - 请参阅 "Expanding the Results View will enumerate the IEnumerable"。