繁体   English   中英

循环中的控制台背景颜色受前一个循环的影响

[英]Console background color in a loop is affected by a previous loop

我在 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 次,则不会再发生这种情况。 我猜这可能与终端 window 有关,您可能无法复制它,所以这是我得到的截图: http://i.imgur.com/2WeaZ4k.png

有谁知道为什么会这样跳线以及如何防止它? 谢谢!

我遇到了类似的问题,并且使用了flush命令使它消失了。 看看这段代码是否对您有用。

    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();
    }
public static void WriteInColor(object args, ConsoleColor? foreground = null, ConsoleColor? background = null)
{
    ConsoleColor prevForeground = Console.ForegroundColor;
    ConsoleColor prevBackground = Console.BackgroundColor;
    Console.ForegroundColor = foreground.HasValue ? (ConsoleColor)foreground : prevForeground;
    Console.BackgroundColor = background.HasValue ? (ConsoleColor)background : prevBackground; ;
    Console.Write(args);
    Console.ForegroundColor = prevForeground;
    Console.BackgroundColor = prevBackground;
    Console.Out.Flush();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM