C#-为什么此 if 语句会删除 StreamReader 输出上的换行符?

标签 c# if-statement while-loop streamreader console.writeline

StreamReader reader = new StreamReader("randomTextFile.txt");
string line = "";

while (line != null)
{
    line = reader.ReadLine();

    if (line != null)
    {
        Console.WriteLine(line);
    }
}

reader.Close();
Console.ReadLine();

在上面的代码中,while 语句内有一个 if 语句,尽管它们指定了相同的内容 (line != null)。如果我删除所说的 if 语句,则会在 txt 文件内容后面添加一个新行(而不是“11037”,控制台将显示“11037”+一个空行)。

最佳答案

while-loop退出条件仅在调用时才会检查,因此在每次迭代开始时检查,而不是每次在其范围内检查。

MSND: the test of the while expression takes place before each execution of the loop

你可以使用这个循环:

string line;
using (var reader = new StreamReader("randomTextFile.txt"))
{
    while ((line = reader.ReadLine()) != null)
    {
        Console.WriteLine(line);
    }
}

您还应该在每个实现 IDisposable 的对象上使用如上所示的 using 语句。这样可以确保非托管资源得到处置。


根据Console.WriteLine特定问题,即使值为null,为什么它会写入新行,那就是 documented :

If value is null, only the line terminator is written to the standard output stream.

关于C#-为什么此 if 语句会删除 StreamReader 输出上的换行符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34199518/

相关文章:

c# - 关于不同的编码风格/指南

java - 在 do while 循环中检查条件的有效方法?

javascript - 在 if 语句中声明或不声明函数的原因

bash - 你怎么能一遍又一遍地在 bash 中运行命令直到成功?

c# - C# Auto Mapper 的性能问题

c# - 在 Unity Animator 中使用 "Any State"的问题

c# - 将 TFS REST API 与存储查询一起使用时是否会编译?

performance - 德尔福性能: Case Versus If

php - PHP while循环中MYSQL更新和删除查询

python - 退出在 python shell 中编写的正在运行的 while 循环