【问题标题】:C#: How many times is foreach master value called?C#:foreach 主值调用了多少次?
【发布时间】:2009-08-16 09:43:07
【问题描述】:

如果我有这个代码:

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

myString.ToLowerInvariant() 会被调用多少次?一次(我假设)还是多次?

【问题讨论】:

    标签: c# loops foreach


    【解决方案1】:

    简答:一次

    长答案:

    代码被编译成下面的 IL。您可以自己尝试编译 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
    

    在 L_0021 到 L_002c 行检查实际的循环条件,然后在 L_002e 行进行跳转,如果尚未处理所有字符,则执行该跳转。请注意,它会跳转到 ToLowerInvariant 调用之后的 L_0013。

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 2010-10-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-11
        • 2011-10-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多