C#与Foreach和for(不是性能)之间的区别

Rad*_*sko 5 c# foreach visual-studio-2008


前段时间我读到foreach使用对象的"副本",因此它可以用于信息检索而不是更新.我没有得到它,因为完全可以遍历类列表并更改其字段.谢谢!

Jon*_*eet 9

可能已经阅读过的内容是,您无法在使用循环进行迭代时修改集合,foreach而您可以(如果您小心)使用for循环.例如:

using System;
using System.Collections.Generic;

class Test
{
    static void Main()
    {
        var list = new List<int> { 1, 4, 5, 6, 9, 10 };


        /* This version fails with an InvalidOperationException
        foreach (int x in list)
        {
            if (x < 5)
            {
                list.Add(100);
            }
            Console.WriteLine(x);
        }
         */

        // This version is okay
        for (int i = 0; i < list.Count; i++)
        {
            int x = list[i];
            if (x < 5)
            {
                list.Add(100);
            }
            Console.WriteLine(x);            
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

如果那不是你所指的,请提供更多细节 - 很难解释你所读到的内容而不知道它究竟是什么.