我在前轮的内部有一个while循环。在我的while循环中,description变量返回数据,但是在循环之外,它是空的,我在c#上是新的,所以我不完全理解为什么,你能帮我吗?
以下是代码:
if (!String.IsNullOrEmpty(path))
{
// Read each line of the file into a string array. Each element
// of the array is one line of the file.
string[] logs = System.IO.File.ReadAllLines(path);
string[] confFile = System.IO.File.ReadAllLines(this.confPath);
string description;
// read each line of the log file
foreach (string log in logs)
{
if (log.Contains("ERROR"))
{
nextLine = index + 1;
descriptionLine = index + 2;
var firstLine = log;
var secondLine = logs[nextLine];
description = logs[descriptionLine];
while (description.Contains("at") || description.Contains("---"))
{
description = logs[descriptionLine++];
}
if (!confFile.Any(s => s.Contains(secondLine)))
{
using (StreamWriter sw = File.AppendText(this.confPath))
{
sw.WriteLine(string.Format("{0},{1},{2}", firstLine, secondLine, description));
}
}
}
index++;
}
}
发布于 2022-07-04 14:58:57
问题是,您在仍然循环时修改while循环条件,并且变量赋值是在索引增量之前进行的。
description = logs[descriptionLine++];
这使得循环检查前一行内容的条件,同时用当前迭代修改描述的内容。
让我们假设您的logs[]
是由以下3行简单代码组成的,我们从descriptionLine = 0
开始
line 0: blah blah at blah
line 1: blah blah at blah
line 2: something else
现在,
description = logs[0] // "line 0: blah blah at blah"
让我们看看while循环条件:
while (description.Contains("at") || description.Contains("---")) { ... }
这个条件是满足的,因为描述暂时包含了单词"at",我们进入循环体:
description = logs[descriptionLine++];
您使用的延迟的++
增量运算符使descriptionLine
变量首先计算、和,然后递增。这意味着description
变量的赋值是在descriptionLine
值从0
增加到1
之前进行的。
现在(这很重要),我们使用一个不变的 description
从第一个循环进入第二个循环。当我们开始第二次迭代时,description
的值仍然是相同的,因此我们进入了循环体,但是descriptionLine
值从0
增加到了1
。延迟的++
增量运算符再次造成了这个问题:
description = logs[1] // "line 1: blah blah at blah"
但是当我们脱离循环时,descriptionLine
是2。最后,我们进入第三次也是最后一次迭代。
while (description.Contains("at") || description.Contains("---"))
description
是"line 1: blah blah at blah"
,我们进入身体,但我们在第三次迭代,我们不应该进入!相反,这种情况会发生:
description = logs[2] // "line 2: something else"
我们做了另一个任务,从现在起,descriptionLine
从1
增加到2
。
https://stackoverflow.com/questions/72857413
复制相似问题