首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >c#无法在while循环之外获得变量的值

c#无法在while循环之外获得变量的值
EN

Stack Overflow用户
提问于 2022-07-04 13:18:42
回答 1查看 102关注 0票数 0

我在前轮的内部有一个while循环。在我的while循环中,description变量返回数据,但是在循环之外,它是空的,我在c#上是新的,所以我不完全理解为什么,你能帮我吗?

以下是代码:

代码语言:javascript
运行
复制
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++;
    }
}
EN

回答 1

Stack Overflow用户

发布于 2022-07-04 14:58:57

问题是,您在仍然循环时修改while循环条件,并且变量赋值是在索引增量之前进行的。

代码语言:javascript
运行
复制
description = logs[descriptionLine++];

这使得循环检查前一行内容的条件,同时用当前迭代修改描述的内容。

让我们假设您的logs[]是由以下3行简单代码组成的,我们从descriptionLine = 0开始

代码语言:javascript
运行
复制
line 0: blah blah at blah
line 1: blah blah at blah
line 2: something else

现在,

代码语言:javascript
运行
复制
description = logs[0] // "line 0: blah blah at blah"

让我们看看while循环条件:

代码语言:javascript
运行
复制
while (description.Contains("at") || description.Contains("---")) { ... }

这个条件是满足的,因为描述暂时包含了单词"at",我们进入循环体:

代码语言:javascript
运行
复制
description = logs[descriptionLine++];

您使用的延迟的++增量运算符使descriptionLine变量首先计算,然后递增。这意味着description变量的赋值是在descriptionLine值从0增加到1之前进行的。

现在(这很重要),我们使用一个不变的 description从第一个循环进入第二个循环。当我们开始第二次迭代时,description的值仍然是相同的,因此我们进入了循环体,但是descriptionLine值从0增加到了1。延迟的++增量运算符再次造成了这个问题:

代码语言:javascript
运行
复制
description = logs[1] // "line 1: blah blah at blah"

但是当我们脱离循环时,descriptionLine是2。最后,我们进入第三次也是最后一次迭代。

代码语言:javascript
运行
复制
while (description.Contains("at") || description.Contains("---"))

description"line 1: blah blah at blah",我们进入身体,但我们在第三次迭代,我们不应该进入!相反,这种情况会发生:

代码语言:javascript
运行
复制
description = logs[2] // "line 2: something else"

我们做了另一个任务,从现在起,descriptionLine1增加到2

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72857413

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档