首页 > 解决方案 > 清除最后一行,并在控制台应用程序中替换它?

问题描述

我已经看过这个问题发布了几次,但我访问过的问题对我来说没有一个可靠的答案。我在下面编写了一个虚拟应用程序只是为了尝试一下,我注意到它有一些问题。

它将用列表中的下一行替换新行,问题是如果上一行比新行长,您仍然可以看到上一行的结尾。

如果你运行下面的代码,你会在最后看到这个,它应该写一些类似的东西,How would did your new hat cost?但写的东西更像How would did your new hat cost?it?是包括前一行的结尾。

static void Main(string[] args)
{
    Console.CursorVisible = false;
    Console.WriteLine();

    var myLines = new List<string>
    {
        "I like dogs, but not cats.",
        "Want to get an icecream tomorrow?",
        "I would like to go to the park.",
        "If I was arrested, would you visit?",
        "How much did your new hat cost?"
    };

    foreach (var line in myLines)
    {
        Console.WriteLine($"  [{DateTime.Now.ToShortTimeString()}] Processing: " + line);
        Console.SetCursorPosition(0, Console.CursorTop - 1);
        Thread.Sleep(new Random().Next(200, 900));
    }

    Console.ReadKey(true);
}

标签: c#.net

解决方案


将您的 foreach 循环修改为如下所示:

 foreach (var line in myLines)
        {
            Console.SetCursorPosition(0, Console.CursorTop - 1);
            ClearCurrentConsoleLine();
            Console.WriteLine($"  [{DateTime.Now.ToShortTimeString()}] Processing: " + line);
            Thread.Sleep(new Random().Next(200, 900));
        }

并使用以下方法:

public static void ClearCurrentConsoleLine()
    {
        int currentLineCursor = Console.CursorTop;
        Console.SetCursorPosition(0, Console.CursorTop);
        Console.Write(new string(' ', Console.WindowWidth));
        Console.SetCursorPosition(0, currentLineCursor);
    }

我已经习惯了以下来实现这个解决方案: Con Console.Clear 可以用来只清除一行而不是整个控制台吗?


推荐阅读