首页 > 解决方案 > foreach 循环中的 C# 奇怪行为

问题描述

经过一天的故障排除后,我设法将问题浓缩为这一小段代码。有人可以向我解释为什么这不起作用吗?当显示消息框时,我希望 [markets] 为 0 2 4 6,[city] [county] 和 [streets] 为 0 1 2 3。

        private void pieceoftestcode()
        {
            string[] county = new string[4];
            string[] city = new string[4];
            string[] markets = new string[4];
            string[] streets = new string[4];
            string[] items = new string[4] { "apple", "banana", "pineapple", "juice" };
            string[] value = new string[4];
            foreach (string item in items)
            {
                for (int i = 0; i <= 3; i++)
                {
                    if (item == "apple")
                        value[i] = (2 * i).ToString();
                    else
                        value[i] = i.ToString();
                }

                if (item == "apple")
                    markets = value;
                else if (item == "banana")
                    streets = value;
                else if (item == "pineapple")
                    county = value;
                else
                    city = value;
            }
            MessageBox.Show("test");
        }

我正在遍历 foreach 循环中的项目。如果项目是“apple”,那么我希望 [value] 为 0 2 4 6。最初 [markets] 被分配 0 2 4 6。但是,如果我逐步执行代码,似乎第二次foreachloop 被执行,[markets] 被覆盖。这是为什么?我在这里做错了什么?一旦香蕉击中,[markets] 不应该第二次赋值吗?

标签: c#loopsforeach

解决方案


逐渐地,所有各种变量都引用同一个数组 ( value),并且在设置最后一次迭代时将任何值写入该数组。

编写此代码的方法非常相似,可以避免该问题:

    private void pieceoftestcode()
    {
        string[] county = new string[4];
        string[] city = new string[4];
        string[] markets = new string[4];
        string[] streets = new string[4];
        string[] items = new string[4] { "apple", "banana", "pineapple", "juice" };
        string[] value;
        foreach (string item in items)
        {
            if (item == "apple")
                value = markets;
            else if (item == "banana")
                value = streets;
            else if (item == "pineapple")
                value = county;
            else
                value = city;
            for (int i = 0; i <= 3; i++)
            {
                if (item == "apple")
                    value[i] = (2 * i).ToString();
                else
                    value[i] = i.ToString();
            }


        }
        MessageBox.Show("test");
    }

现在,每次循环value都被分配一个对不同数组1的引用,因此for循环不会覆盖它之前的工作。


1假设items不包含任何重复项目,也不包含超过一个非苹果、-香蕉或-菠萝项目。


推荐阅读