gpt4 book ai didi

c# - 为什么在 GetCurrent 之前调用 IEnumerator.MoveNext?

转载 作者:行者123 更新时间:2023-11-30 20:41:40 27 4
gpt4 key购买 nike

我是 IL 的新手,但据我所知,MoveNext 应该在 Current 之前调用,假设我们有这样的 foreach 语句:

foreach (var i in Enumerable.Empty<string>())
{
}

如果我们查看生成的 IL,我们将看到 Current 实际上首先被调用:

IL_0014:  br.s       IL_001f
IL_0016: ldloc.1
IL_0017: callvirt instance !0 class [mscorlib]System.Collections.Generic.IEnumerator`1<string>::get_Current()
IL_001c: stloc.0
IL_001d: nop
IL_001e: nop
IL_001f: ldloc.1
IL_0020: callvirt instance bool [mscorlib]System.Collections.IEnumerator::MoveNext()
IL_0025: stloc.2
IL_0026: ldloc.2
IL_0027: brtrue.s IL_0016
IL_0029: leave.s IL_003b

问题是为什么?

最佳答案

IL_0014:  br.s       IL_001f

根据 MSDN,br.s

Unconditionally transfers control to a target instruction (short form).

引用的地址是调用MoveNext的指令。

IL_001f:  ldloc.1
IL_0020: callvirt instance bool [mscorlib]System.Collections.IEnumerator::MoveNext()

关于c# - 为什么在 GetCurrent 之前调用 IEnumerator.MoveNext?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32146619/

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