备忘-ForEach方法与foreach迭代器使用小区别

class Program
    {
        static void Main(string[] args)
        {
            List<string> ss = new List<string>();
            ss.Add("a");
            ss.Add("b");
            ss.Add("c");
            ss.Add("d");
            ss.Add("e");
            ss.Add("f");
            ss.Add("g");
            ss.Add("h");

            bool re = false;
            int index = 0;

            //ForEach可避免遍历List过程中改变集合出错问题,并且保证遍历到存在的每一个元素
            //原因:委托?
            ss.ForEach(p =>
            {
                index++;
                if (!re)
                {
                    ss.Remove("e");
                    ss.Remove("f");
                    re = true;
                }
                Console.WriteLine(index + ":" + p);
            });

            //谁都知道会出错
            //原因:?
            //foreach (string item in ss)
            //{
            //    index++;
            //    if (!re)
            //    {
            //        re = true;
            //        ss.Remove(item);
            //    }
            //    Console.WriteLine(index + ":" + item);
            //}

            Console.ReadLine();
        }
    }

使用过程中注意:

ForEach方法不可Break;

foreach可以。

性能上孰强孰弱?

 

转载于:https://www.cnblogs.com/wishFreedom/archive/2013/04/18/3028963.html