c# - 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] 不应该第二次赋值吗?
解决方案
逐渐地,所有各种变量都引用同一个数组 ( 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
不包含任何重复项目,也不包含超过一个非苹果、-香蕉或-菠萝项目。
推荐阅读
- angular - 设置离子范围的值但不起作用
- gradle - 在 Gradle 中禁用自动检测运行
- xml - 合并 Maximo 生成的 XSD?
- android - 如何在应用程序中确定暂存或生产 __dev__
- python - Pandas DataFrame 过滤 || 只保留列的连续元素
- javascript - 在窗口调整大小时计算圆圈的大小
- swift - 在 AppDelegate 中执行 segue
- powershell - 在 PowerShell 中使用变量将多个参数传递给外部程序
- wpf - .Net Core WPF 是否支持“单击一次”?
- python - 如何避免错误:selenium.common.exceptions.SessionNotCreatedException: Message: session not created from tab crashed