"object is enumerated" 在 C# 中是什么意思?

What does "object is enumerated" mean in C#?

我最近一直在阅读有关延迟执行、LINQ、一般查询等的文章和文档,并且经常出现短语“对象被枚举”。有人可以解释枚举对象时会发生什么吗?

例子article.

This method is implemented by using deferred execution. The immediate return value is an object that stores all the information that is required to perform the action. The query represented by this method is not executed until the object is enumerated either by calling its GetEnumerator method directly or by using foreach in Visual C#

枚举的一般说明

IEnumerable是一个接口,通常由C#中的collection类型实现。例如 ListQueueArray.

IEnumerable 提供了一种方法 GetEnumerator,其中 return 是 IEnumerator.

类型的 object

IEnumerator 基本上表示指向 collection 中元素的“向前移动指针”。 IEnumerator 有:

  • 属性 Current,return 当前指向的 object(例如 collection 中的第一个 object) .
  • 一种方法MoveNext,它将指针移动到下一个元素。调用它后,Current 将保存对 collection 中第二个 object 的引用。如果 collection.
  • 中没有更多元素,MoveNext 将 return false

每当执行 foreach 循环时,检索 IEnumerator 并为每次迭代调用 MoveNext - 直到最终 returns false .您在循环 header 中定义的变量由 IEnumeratorCurrent.

填充

编译一个 foreach 循环

感谢@Llama

此代码...

List<int> a = new List<int>();
foreach (var val in a)
{
    var b = 1 + val;
}

被编译器转换成这样:

List<int> list = new List<int>();
List<int>.Enumerator enumerator = list.GetEnumerator();
try
{
    while (enumerator.MoveNext())
    {
        int current = enumerator.Current;
        int num = 1 + current;
    }
} finally {
    ((IDisposable)enumerator).Dispose();
}

引用

The query represented by this method is not executed until the object is enumerated either by calling its GetEnumerator method directly or by using foreach in Visual C#.

例如,只要将 object 放入 foreach 循环中,就会自动调用

GetEnumerator。当然,其他功能,例如Linq 查询,也可以通过显式(调用 GetEnumerator)或隐含在某种循环中,从您的 collection 中检索 IEnumerator,就像我在上面的示例中所做的那样。

我认为您只需要很好地理解 LINQ 查询的延迟执行与立即执行。

延迟执行:当您编写 LINQ 查询时,它仅在您实际访问结果时执行 - 延迟直到您 运行 代码迭代,即 foreach 以上结果。这是默认行为。

立即执行:我们可以通过向查询附加 ToList() 或类似方法来强制执行此操作(您会在 C# 代码中经常看到)。