zoukankan      html  css  js  c++  java
  • 还是不能偷懒ForEach陷阱

    class Program
        {
            static void Main(string[] args)
            {
                List<string> st = new List<string>();
                st.Add("A");
                st.Add("B");
                //st.Add("C");
    
                bool isF = false;
                st.ForEach(p =>
                {
                    if (!isF)
                    {
                        st.Remove("A");
                        isF = true;
                    }
                    Console.WriteLine(p);
                });
            }
        }

    打印如下:

    再来比较(使用的同学注意喽):

    class Program
        {
            static void Main(string[] args)
            {
                List<string> st = new List<string>();
                st.Add("A");
                st.Add("B");
                st.Add("C");
    
                bool isF = false;
                st.ForEach(p =>
                {
                    if (!isF)
                    {
                        st.Remove("B");
                        isF = true;
                    }
                    Console.WriteLine(p);
                });
            }
        }


    打印如下:

    实际项目中使用ForEach方法的同学注意咯!小心数量为2时移除第一元素后面就没有继续遍历咯?原因呢?高手在哪里?

  • 相关阅读:
    3.31上午英语视频
    3.30上午
    leetcode 38
    leetcode 36
    leetcode 28
    leetcode 27
    leetcode 26
    leetcode 24
    leetcode 21
    leetcode 20
  • 原文地址:https://www.cnblogs.com/wishFreedom/p/3030452.html
Copyright © 2011-2022 走看看