c# - 清除最后一行,并在控制台应用程序中替换它?
问题描述
我已经看过这个问题发布了几次,但我访问过的问题对我来说没有一个可靠的答案。我在下面编写了一个虚拟应用程序只是为了尝试一下,我注意到它有一些问题。
它将用列表中的下一行替换新行,问题是如果上一行比新行长,您仍然可以看到上一行的结尾。
如果你运行下面的代码,你会在最后看到这个,它应该写一些类似的东西,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);
}
解决方案
将您的 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 可以用来只清除一行而不是整个控制台吗?
推荐阅读
- python - 计算python中特定列中数字的出现次数
- c++ - 如何在自定义对象的 << 运算符中添加自定义前缀
- python - 在 sklearn 预测器(ParallelPostFit 包装器)上使用 dask Parallel post fit
- swift - 如何通过 NSUserUnixTask 传递参数,然后通过脚本访问?
- sql-server - 用 WHERE 加入总和
- twilio - 让 Twilio 等待 15 秒,然后继续流动
- javascript - 来自 Illustrator 的 UIBezierPath,参考坐标问题
- php - 作曲家更新无法解决依赖关系
- angular - PrimeNG 桌子弹性尺寸
- javascript - 命令行参数问题——跳过可选函数参数?