还是不能偷懒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时移除第一元素后面就没有继续遍历咯?原因呢?高手在哪里?

原文地址:https://www.cnblogs.com/wishFreedom/p/3030452.html