zoukankan      html  css  js  c++  java
  • 备忘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可以。

    性能上孰强孰弱?

  • 相关阅读:
    day3
    day2
    day1-存储
    day5-iptables
    MySQL之补充
    11.18
    11.17
    junit基础学习之-测试controller层(2)
    junit基础学习之-简介(1)
    外键和级联
  • 原文地址:https://www.cnblogs.com/wishFreedom/p/3028963.html
Copyright © 2011-2022 走看看