2014-10-07 3 views
-1

Console.WriteLine()을 사용하는 프로그램이 있습니다. 프로그램의 여러 위치에서 사용자에게 출력 할 수 있습니다. 콘솔 응용 프로그램에서 마지막 출력 행을 출력하는 방법이 있습니까? 모든 Console.WriteLine(); 카운터를 증가시키지 않고.콘솔 응용 프로그램의 줄 번호를 찾으십니까?

Console.WriteLine("Foo"); 
Console.WriteLine("Foo Bar"); 
Console.WriteLine("Bar"); 
Console.WriteLine("Bar Foo"); 

출력 :

푸 바

예를 들어, 다음 코드 "바 푸"의 예제 프로그램이 될 것 4. 다음 행으로 인쇄 한 것 바

바 Foo

+0

매우 cood 기술 : 그래서 당신은 행 번호의 0부터 시작하는 인덱스으로 커서의 위치를 ​​사용할 수 있습니다 [어떻게 현재의 행 번호를 얻을 수 - messagebox.show에서 예를 들어, 사용 (HTTP : //stackoverflow.com/questions/12556767/how-to-get-current-line-number-for-example-use-at-messagebox-show) –

답변

0

.Net 4.5에 소개되는 CallerLineNumber을 사용할 수 있습니다. 당신이 닷넷의 낮은 버전을 사용해야하는 경우 사용할 수있는

WriteLine("Foo"); 
WriteLine("Foo Bar"); 
WriteLine("Bar"); 
WriteLine("Bar Foo"); 

: 당신은 단순히 호출 할 수 있습니다

static void WriteLine(string message, [CallerLineNumber] int lineNumber = 0) 
{ 
    Console.WriteLine(lineNumber + ": " + message); 
} 

그리고 당신의 소스 코드에

좋아 :
당신은 이런 일이있을 수 있습니다

static void WriteLine(string message) 
{ 
    StackFrame callStack = new StackFrame(1, true); 
    var lineNumber = callStack.GetFileLineNumber(); 
    Console.WriteLine(lineNumber + ": " + message); 
} 

는 그리고 다시는 호출해야합니다

WriteLine("Foo"); 
WriteLine("Foo Bar"); 
WriteLine("Bar"); 
WriteLine("Bar Foo"); 
1

아니요 당신은 그것을 추적하기 위해 커스텀이 필요합니다. 그러나 내부화 할 수 있으며 반복되는 카운터 논리를 피하기 위해 Console.WriteLine을 래핑하는 고유 한 클래스를 만들 수 있습니다.

0

실제로 Console.WriteLine()을 수행 할 때마다 커서도 움직입니다. 여기에 게시

 Console.WriteLine("Foo" + (Console.CursorTop+1)); 
     Console.WriteLine("Foo Bar" + (Console.CursorTop + 1)); 
     Console.WriteLine("Bar" + (Console.CursorTop + 1)); 
     Console.WriteLine("Bar Foo" + (Console.CursorTop + 1)); 
관련 문제