2010-03-30 3 views

답변

7

이 시도 :

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(); 
    } 
} 
+0

니스는 예상대로 줄 바꿈 문자를 처리합니다. – AMissico

+0

Console.Indent ++와 같이 구문을 자연스럽게 만들기 위해 콘솔을 "확장"하는 모든 사람. – AMissico

+0

@AMissico : 아니요, 콘솔은 봉인되어 있습니다. –

2

나는 보통 단지 (내 응용 프로그램 클래스 내에서) 같은 것을 할 : 예를 들어, 다음

static TextWriter tw; 
static int indentLevel = 0; 

static void Indend() 
{ 
    indentLevel++; 
} 

static void Outdent() 
{ 
    indentLevel--; 
} 

static void WriteLine(string s) 
{ 
    tw.WriteLine(new string('\t', indentLevel) + s); 
} 

static void WriteLine() 
{ 
    tw.WriteLine(); 
} 

using (tw = new StreamWriter(outputName)) 
{ 
    WriteLine(string.Format("namespace {0}", nameSpace)); 
    WriteLine("{"); 

    Indend(); 

    foreach (string s in dataSourceItems) 
     GenerateProc(s); 

    Outdent(); 

    WriteLine("}"); 
} 

원하는 경우 분명히 별도의 클래스로 캡슐화 할 수 있습니다.

9

System.CodeDom.Compiler.IndentedTextWriter

이 System.dll을에 닷넷 프레임 워크에 내장되어 있지만 슈퍼 강력하지 않다 . 문자열에서 개행 문자가없는 것과 같이 제한된 용도로 작동해야합니다.

static void Main(string[] args) 
    { 
     using (System.CodeDom.Compiler.IndentedTextWriter writer = new System.CodeDom.Compiler.IndentedTextWriter(Console.Out, " ")) 
     { 
      Console.SetOut(writer); 
      writer.Indent = 0; 
      writer.WriteLine("test"); 
      writer.Indent = 1; 
      writer.WriteLine("What happens\nif there are line-\nbreak in the middle?"); 
      writer.Indent = 2; 
      writer.WriteLine("another test"); 
      writer.Indent = 3; 
      writer.WriteLine("and another test"); 
      writer.Indent = 0; 
      writer.WriteLine("hello"); 
     } 
     Console.ReadLine(); 
    } 
+1

+1 좋은 예제 코드 – AMissico