经过一天的故障排除后,我设法将问题浓缩为这一小段代码。有人可以向我解释为什么这不起作用吗?当显示消息框时,我希望 [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");
}
Run Code Online (Sandbox Code Playgroud)
我在 foreach 循环中遍历项目。如果项目是“apple”,那么我期望 [value] 为 0 2 4 6。最初 [markets] 被分配 0 2 4 6。但是,如果我一步一步地执行代码,似乎第二次foreachloop 被执行,[markets] 被覆盖。这是为什么?我在这里做错了什么?[市场] 不应在香蕉击中后再次赋值,对吗?
逐渐地,所有不同的变量都引用同一个数组 ( 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");
}
Run Code Online (Sandbox Code Playgroud)
现在,每次循环value都会被分配一个对不同数组1 的引用,因此for循环不会覆盖其之前的工作。
1假设items不包含任何重复项目,也不包含超过一项非苹果、香蕉或菠萝项目。