是否有人知道用于控制台的TextWriter,它了解如何缩进/缩进并具有设置缩进级别的能力。

最佳答案

试试这个:

class MyConsole : TextWriter {
    TextWriter mOldConsole;
    bool mDoIndent;

    public MyConsole() {
        mOldConsole = Console.Out;
        Console.SetOut(this);
    }

    public int Indent { get; set; }

    public override void Write(char ch) {
        if (mDoIndent) {
            mDoIndent = false;
            for (int ix = 0; ix < Indent; ++ix) mOldConsole.Write("  ");
        }
        mOldConsole.Write(ch);
        if (ch == '\n') mDoIndent = true;
    }

    public override System.Text.Encoding Encoding {
        get { return mOldConsole.Encoding; }
    }
}


用法示例:

class Program {
    static MyConsole Output = new MyConsole();
    static void Main(string[] args) {
        Console.WriteLine("Hello");
        Output.Indent++;
        Console.WriteLine("world");
        Output.Indent--;
        Console.WriteLine("Back");
        Console.ReadLine();
    }
}

09-19 16:41