有什么方法可以编辑/重写某些已经由 Console.PrintLine() 方法打印的行?我必须能够编辑提示中显示的任何行。
这是我试图运行的代码的示例,可能看起来像:
public static void RewriteLine(LineNr, Text)
{
//Code
}
Console.WriteLine("Text to be rewritten");
Console.Writeline("Just some text");
RewriteLine(1, "New text");
根据先前代码的输出显示我要重写哪一行的示例:
Text to be rewritten//这一行(已经被Console.WriteLine()方法执行过)应该替换为:“New text”
只是一些文字
最佳答案
它应该是这样的:
public static void RewriteLine(int lineNumber, String newText)
{
int currentLineCursor = Console.CursorTop;
Console.SetCursorPosition(0, currentLineCursor - lineNumber);
Console.Write(newText); Console.WriteLine(new string(' ', Console.WindowWidth - newText.Length));
Console.SetCursorPosition(0, currentLineCursor);
}
static void Main(string[] args)
{
Console.WriteLine("Text to be rewritten");
Console.WriteLine("Just some text");
RewriteLine(2, "New text");
}
发生的事情是你改变了光标位置并在那里写了一些东西。您应该添加一些代码来处理长字符串。
关于C# - 在程序运行时重写/编辑行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34423986/