这个问题让我很困惑。我有一个在循环中共享的变量,它没有递增。
有问题的变量是 elrObject.currentLocation。有两种方法可以递增它 - 如果 XML 元素为空或不为空。
代码如下:
if (reader.Name == "Cell")
{
if (reader.IsEmptyElement)
{
Response.Write("i ran<br>");
elrObject.currentLocation++;
}
else
{
while (reader.Read())
{
if (reader.IsStartElement())
{
//labels
if (elrObject.currentLocation >= elrObject.index && elrObject.currentLocation <= elrObject.index + elrObject.colSpan)
Response.Write("i ran again<br>");
Response.Write(elrObject.currentLocation + "<br>");
elrObject.currentLocation++;
}
if (reader.Name == "Cell")
break;
}
}
}
我得到的输出是:
0
1
2
3
5
数字 4 是当 XML 元素为空并且运行顶部循环时。我正在递增变量,但它不会显示数字 4,它会完全跳过它并转到 5。我确信上层循环在下层循环之前运行正常,因为以下循环也在运行:
我跑了
我又跑了
这证实了上层循环在下层循环之前运行……但是数字 4 正在跳过自己!我真的很感激这方面的帮助。
最佳答案
不应该显示数字 4。您没有
Response.Write(elrObject.currentLocation + "<br>");
在
if (reader.IsEmptyElement)
阻止。
关于c# - 变量在多个循环内不递增,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14944430/