是否可以以不同颜色显示格式化输出:
console.WriteLine(“First {0} second{1} ”, firstString, secondString)
我想在输出时显示变化,比如用一种颜色显示firstString,另一种颜色显示secondString。
是否可以以不同颜色显示格式化输出:
console.WriteLine(“First {0} second{1} ”, firstString, secondString)
如果你想在一行代码中使用不同的颜色,应该使用Console.Write()
方法,像这样写:
Console.ForegroundColor = ConsoleColor.White;
Console.Write("First ");
Console.ForegroundColor = ConsoleColor.Blue;
Console.Write("{0} ", firstString);
Console.ForegroundColor = ConsoleColor.White;
Console.Write("second ");
Console.ForegroundColor = ConsoleColor.Green;
Console.Write("{0} ", secondString);
Console.Write()
方法并设置控制台的颜色,如下所示:class Program {
static void Main( string[] args ) {
PrintColoredString( "First", "firstString", ConsoleColor.Green );
PrintColoredString( "second", "secondString", ConsoleColor.Cyan );
Console.ResetColor();
Console.ReadKey();
}
private static void PrintColoredString(string key, string value, ConsoleColor color) {
Console.ForegroundColor = color;
Console.Write( "{0} {1} ", key, value );
}
}
可以使用 Console.ForegroundColor
和 Console.BackgroundColor
来实现,但需要将 Console.WriteLine
调用拆分为多个 Console.Write 调用,以避免在组件之间出现换行符。
请注意线程安全性,确保不会在输出不同颜色的行时出现重叠 - 这可能会让你非常不舒服。
你可以使用
Console.BackgroundColor = ConsoleColor.Blue;
Console.ForegroundColor = ConsoleColor.White;
请参见C#控制台颜色。
据我所知,在同一行中不可能使用多种颜色。