들여 쓰기/들여 쓰기 방법을 이해하고 들여 쓰기 수준을 설정할 수있는 기능을 가진 콘솔 용 TextWriter를 가지고 있거나 알고있는 사람이 있습니까?들여 쓰기/들여 쓰기/들여 쓰기 수준을 이해하는 .NET Console TextWriter
5
A
답변
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();
}
}
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
니스는 예상대로 줄 바꿈 문자를 처리합니다. – AMissico
Console.Indent ++와 같이 구문을 자연스럽게 만들기 위해 콘솔을 "확장"하는 모든 사람. – AMissico
@AMissico : 아니요, 콘솔은 봉인되어 있습니다. –