2013-10-12 37 views
1

在OS X 10.7.5上的Xamarin Studio中處理c#控制檯應用程序時發現了一個奇怪的錯誤。如果我在循環的一次迭代中更改背景顏色,如果在此之前有另一個循環,顏色有時會跳下去。例如:循環中的控制檯背景顏色受前一循環的影響

for (int i = 0; i < 18; i++) { 
    Console.WriteLine (i); 
} 
for (int i = 0; i < 8; i++) { 
    if (i == 5) { 
     Console.BackgroundColor = ConsoleColor.Green; 
     Console.WriteLine ("green"); 
     Console.ResetColor(); 
    } else { 
     Console.WriteLine (i); 
    } 
} 

如果您運行該代碼,綠色背景將跳過一行。但是,如果您將第一個循環更改爲運行17次(或更少)而不是18次,則不會再發生這種情況。我猜這可能與終端窗口有關,你可能無法複製它,所以這裏是我得到的屏幕截圖:http://i.imgur.com/2WeaZ4k.png

有誰知道爲什麼線路跳轉那樣以及如何防止?謝謝!

+0

我有在Windows(Visual Studio中)同樣的問題 –

回答

0

我有一個類似的問題,一個刷新命令使它消失。看看這段代碼是否適合你。

public static void WriteInColor(string format, ConsoleColor foreground, ConsoleColor background, params object[] args) 
    { 
     ConsoleColor prevForeground = Console.ForegroundColor; 
     ConsoleColor prevBackground = Console.BackgroundColor; 
     Console.ForegroundColor = foreground; 
     Console.BackgroundColor = background; 
     Console.Write(format, args); 
     Console.ForegroundColor = prevForeground; 
     Console.BackgroundColor = prevBackground; 
     Console.Out.Flush(); 
    } 
+0

你不會得到太多出刷新它的,除了你可能會稍微改變時間:http://referencesource.microsoft.com/#mscorlib /system/io/__consolestream.cs,109 – poizan42