控制台颜色:同一行中是否有1个以上?

Dan*_*Dan 2 c# console

使用方法:

public static void ColoredConsoleWrite(ConsoleColor color, string text)
    {
    ConsoleColor originalColor = Console.ForegroundColor;
    Console.ForegroundColor = color;
    Console.Write(text);
    Console.ForegroundColor = originalColor;
}
Run Code Online (Sandbox Code Playgroud)

和:

ColoredConsoleWrite(ConsoleColor.Blue, $"My favorite fruit: Apple");

有没有一种方法可以使苹果保持红色,同时保留我最喜欢的水果:蓝色?

Jim*_*hel 5

是的,可以在同一行上以不同的颜色写文本。但是您必须为每种不同的颜色更改前景色。也就是说,如果要用蓝色写“我最喜欢的水果:”,用红色写“ Apple”,那么您必须执行以下两项Write操作:

var originalColor = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.Blue;
Console.Write("My farorite fruit: ");
Console.ForegroundColor = ConsoleColor.Red;
Console.Write("Apple");
Console.ForegroundColor = originalColor;
Run Code Online (Sandbox Code Playgroud)

如果您想通过单个调用完成此操作,则需要某种方式在字符串中进行定义。.NET Framework不提供此类功能。可以构建这样的东西。这将涉及编写类似于String.Format所使用的字符串解析器,在其中定义占位符,并为其提供值作为参数。

也许更简单的方法是编写一个采用颜色和字符串对列表的方法,例如:

public class ColoredString
{
    public ConsoleColor Color;
    public String Text;

    public ColoredString(ConsoleColor color, string text)
    {
        Color = color;
        Text = text;
    }
}

public static void WriteConsoleColor(params ColoredString[] strings)
{
    var originalColor = Console.ForegroundColor;
    foreach (var str in strings)
    {
        Console.ForegroundColor = str.Color;
        Console.Write(str.Text);
    }
    Console.ForegroundColor = originalColor;
}

public void DoIt()
{
    WriteConsoleColor(
        new ColoredString(ConsoleColor.Blue, "My favorite fruit: "),
        new ColoredString(ConsoleColor.Red, "Apple")
    );
}
Run Code Online (Sandbox Code Playgroud)