我对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


  无条件地将控制权转移到目标指令(短格式)。


引用的地址是调用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/

10-11 20:36