突出显示WriteLine中的文本

问题描述

我要在WriteLine中突出显示文本,我该怎么做? 例如Console.Write(“ Hello World”);我希望“世界”为绿色。 你们能帮我吗?

解决方法

您可以使用Console.BackgroundColor属性。

最佳做法是:

// save the previous color
var prevColor = Console.BackgroundColor;

// set your color
Console.BackgroundColor = ConsoleColor.Green;

Console.Write("Hello World"); 

Console.BackgroundColor = prevColor ;

// finally,reset all colors to originals.
Console.ResetColor();
,

示例(我的默认文本颜色为绿色)

static void Main(string[] args)
{
    Console.Write("Hello");

    var prevColor = Console.ForegroundColor;

    // Set new text's color
    Console.ForegroundColor = ConsoleColor.Yellow;

    Console.Write(" World");

    // Restore old text's color
    Console.ForegroundColor = prevColor;

    Console.ReadLine();
}

Console text color