【问题标题】:Is there a function to read the entire console?是否有读取整个控制台的功能?
【发布时间】:2020-05-04 13:23:18
【问题描述】:

我正在用 C# 编写一个程序,我想让一个程序做这样的事情:

while (true)
{
    var Key = Console.ReadKey();
    if (Key.Key == ConsoleKey.Backspace)
    {
        Console.SetCursorPosition(0, Console.CursorTop - 1);
        Console.Write(new string(' ', Console.WindowWidth));
    }
    else
    {
        Console.ReadLine();
    }
}

然后执行以下操作:

Console.ReadAllTextInConsole

获取当前控制台窗口中的所有文本并将其放入字符串中。这可能吗?

【问题讨论】:

  • 为什么是while (0 == 0)
  • (0 == 0) 和 (true) 有区别吗?
  • 不,没有,为什么不直接写true
  • 这甚至不是有效的 c# 代码。

标签: c# console console-application


【解决方案1】:

我在没有删除最后一行的情况下做了这个,但它应该可以满足你的要求,试试看:

class Program
{
    static void Main(string[] args)
    {
        var console = new ConsoleV2();

        while (true)
        {
            var input = Console.ReadLine();
            if (input != "print")
            {
                console.WriteLine(input);
            }
            else
            {
                Console.WriteLine(console.GetOutput());
            }
        }
    }
}

public class ConsoleV2
{
    private readonly StringBuilder _stringBuilder;

    public ConsoleV2()
    {
        _stringBuilder = new StringBuilder();
    }

    public void Write(string format, params object[] args)
    {
        _stringBuilder.Append(string.Format(format, args));
        Console.Write(format, args);
    }

    public void WriteLine(string format, params object[] args)
    {
        _stringBuilder.AppendLine(string.Format(format, args));
        Console.WriteLine(format, args);
    }

    public string GetOutput()
    {
        return _stringBuilder.ToString();
    }
}

【讨论】:

    猜你喜欢
    • 2019-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多