Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/299.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 迭代ToList方法与存储在内存中的ToList数据_C#_.net_Visual Studio - Fatal编程技术网

C# 迭代ToList方法与存储在内存中的ToList数据

C# 迭代ToList方法与存储在内存中的ToList数据,c#,.net,visual-studio,C#,.net,Visual Studio,当前的.NET编译器是否以不同的方式处理这些问题 List<string> stuff = GetSomeStuff(); foreach(string thing in stuff) { ... } 如果启用编译器优化,则两组代码将编译为相同的IL。例如,这是使用LinqPad时主方法的IL输出: IL_0000: ldarg.0 IL_0001: call UserQuery.GetSomeStuff IL_0006: callvirt Sy

当前的.NET编译器是否以不同的方式处理这些问题

List<string> stuff = GetSomeStuff();
foreach(string thing in stuff) { ... }

如果启用编译器优化,则两组代码将编译为相同的IL。例如,这是使用LinqPad时主方法的IL输出:

IL_0000:  ldarg.0     
IL_0001:  call        UserQuery.GetSomeStuff
IL_0006:  callvirt    System.Collections.Generic.List<System.String>.GetEnumerator
IL_000B:  stloc.0     
IL_000C:  br.s        IL_0016
IL_000E:  ldloca.s    00 
IL_0010:  call        System.Collections.Generic.List<System.String>.get_Current
IL_0015:  pop         
IL_0016:  ldloca.s    00 
IL_0018:  call        System.Collections.Generic.List<System.String>.MoveNext
IL_001D:  brtrue.s    IL_000E
IL_001F:  leave.s     IL_002F
IL_0021:  ldloca.s    00 
IL_0023:  constrained. System.Collections.Generic.List<>.Enumerator
IL_0029:  callvirt    System.IDisposable.Dispose
IL_002E:  endfinally  
IL_002F:  ret  
IL_0000:ldarg.0
IL_0001:调用UserQuery.GetSomeStuff
IL_0006:callvirt System.Collections.Generic.List.GetEnumerator
IL_000B:stloc.0
IL_000C:br.s IL_0016
IL_000E:ldloca.s 00
IL_0010:调用System.Collections.Generic.List.get_Current
IL_0015:流行音乐
IL_0016:ldloca.s 00
IL_0018:调用System.Collections.Generic.List.MoveNext
IL_001D:brtrue.s IL_000E
IL_001F:离开s IL_002F
IL_0021:ldloca.s 00
IL_0023:受约束。System.Collections.Generic.List.Enumerator
IL_0029:callvirt System.IDisposable.Dispose
IL_002E:最后结束
IL_002F:ret

前者的唯一好处是,如果您想使用
stuff
变量执行其他操作,则前者可能会重复。对于您的代码,您最好使用后者。
IL_0000:  ldarg.0     
IL_0001:  call        UserQuery.GetSomeStuff
IL_0006:  callvirt    System.Collections.Generic.List<System.String>.GetEnumerator
IL_000B:  stloc.0     
IL_000C:  br.s        IL_0016
IL_000E:  ldloca.s    00 
IL_0010:  call        System.Collections.Generic.List<System.String>.get_Current
IL_0015:  pop         
IL_0016:  ldloca.s    00 
IL_0018:  call        System.Collections.Generic.List<System.String>.MoveNext
IL_001D:  brtrue.s    IL_000E
IL_001F:  leave.s     IL_002F
IL_0021:  ldloca.s    00 
IL_0023:  constrained. System.Collections.Generic.List<>.Enumerator
IL_0029:  callvirt    System.IDisposable.Dispose
IL_002E:  endfinally  
IL_002F:  ret