简体   繁体   English

C#:foreach主值调用多少次?

[英]C#: How many times is foreach master value called?

If I have this code: 如果我有此代码:

foreach (Char c in myString.ToLowerInvariant())
{ /* code */ }

How many times will myString.ToLowerInvariant() get called? myString.ToLowerInvariant()将被调用多少次? Once (which I assume) or multiple times? 一次(我假设)还是多次?

Short answer: Once 简短答案:一次

Long answer: 长答案:

The code gets compiled into the following IL. 该代码被编译为以下IL。 You can try it yourself by compiling the C# file and then opening it in ILDASM (distributed with Visual Studio) or .NET Reflector (which can show the disassembled code in many languages and has tooltips for IL instructions with detailed description). 您可以自己编译C#文件,然后在ILDASM(与Visual Studio一起分发)或.NET Reflector(可以显示多种语言的反汇编代码,并提供带有详细说明的IL指令的工具提示)中进行尝试。

L_0008: ldloc.0 
L_0009: callvirt instance string [mscorlib]System.String::ToLowerInvariant()
L_000e: stloc.2 
L_000f: ldc.i4.0 
L_0010: stloc.3 
L_0011: br.s L_0021
L_0013: ldloc.2 
L_0014: ldloc.3 
L_0015: callvirt instance char [mscorlib]System.String::get_Chars(int32)
L_001a: stloc.1 
L_001b: nop 
L_001c: nop 
L_001d: ldloc.3 
L_001e: ldc.i4.1 
L_001f: add 
L_0020: stloc.3 
L_0021: ldloc.3 
L_0022: ldloc.2 
L_0023: callvirt instance int32 [mscorlib]System.String::get_Length()
L_0028: clt 
L_002a: stloc.s flag
L_002c: ldloc.s flag
L_002e: brtrue.s L_0013

The actual loop condition is checked on lines L_0021 to L_002c and then there a jump at line L_002e which is executed if not all characters are processed yet. 在L_0021到L_002c行检查实际的循环条件,然后在L_002e行进行跳转,如果尚未处理所有字符,则执行该跳转。 Note that it jumps to L_0013 which is after the ToLowerInvariant call. 请注意,它在ToLowerInvariant调用之后跳至L_0013。

一次...然后遍历调用返回的每个值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM