写一个小的命令行工具,用不同的颜色输出会很好。这可能吗?


当前回答

下面是一个优雅的实现,它使用了dotnet新的字符串插值特性。

[InterpolatedStringHandler]
public ref struct ConsoleInterpolatedStringHandler
{
    private static readonly Dictionary<string, ConsoleColor> colors;
    private readonly IList<Action> actions;

    static ConsoleInterpolatedStringHandler() =>
        colors = Enum.GetValues<ConsoleColor>().ToDictionary(x => x.ToString().ToLowerInvariant(), x => x);

    public ConsoleInterpolatedStringHandler(int literalLength, int formattedCount)
    {
        actions = new List<Action>();
    }

    public void AppendLiteral(string s)
    {
        actions.Add(() => Console.Write(s));
    }

    public void AppendFormatted<T>(T t)
    {
        actions.Add(() => Console.Write(t));
    }

    public void AppendFormatted<T>(T t, string format)
    {
        if (!colors.TryGetValue(format, out var color))
            throw new InvalidOperationException($"Color '{format}' not supported");

        actions.Add(() =>
        {
            Console.ForegroundColor = color;
            Console.Write(t);
            Console.ResetColor();
        });
    }

    internal void WriteLine() => Write(true);
    internal void Write() => Write(false);

    private void Write(bool newLine)
    {
        foreach (var action in actions)
            action();

        if (newLine)
            Console.WriteLine();
    }
}

要使用它,创建一个类,例如ExtendedConsole:

internal static class ExtendedConsole
{
    public static void WriteLine(ConsoleInterpolatedStringHandler builder)
    {
        builder.WriteLine();
    }

    public static void Write(ConsoleInterpolatedStringHandler builder)
    {
        builder.Write();
    }
}

然后,像这样使用它:

        var @default = "default";
        var blue = "blue";
        var green = "green";
        ExtendedConsole.WriteLine($"This should be {@default}, but this should be {blue:blue} and this should be {green:green}");

其他回答

是的,这很简单,也有可能。定义第一个默认颜色。

Console.BackgroundColor = ConsoleColor.Black;
Console.ForegroundColor = ConsoleColor.White;
Console.Clear();

console . clear()对于设置新的控制台颜色很重要。如果不执行此步骤,则在使用Console.ReadLine()请求值时可以看到组合颜色。

然后你可以改变每个打印的颜色:

Console.BackgroundColor = ConsoleColor.Black;
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Red text over black.");

当完成程序时,记得在完成时重置控制台颜色:

Console.ResetColor();
Console.Clear();

现在对于netcore,我们有另一个问题,如果你想“保留”用户体验,因为终端在每个操作系统上有不同的颜色。

我正在制作一个库,用文本格式解决这个问题:颜色,对齐和更多。请随意使用和贡献。

https://github.com/deinsoftware/colorify/,也可作为NuGet包

Windows/Linux的颜色(深色):

MacOS的颜色(浅色):

上面的注释都是可靠的响应,但是注意它们不是线程安全的。如果您正在用多个线程写入控制台,更改颜色将添加一个竞争条件,可能会产生一些奇怪的输出。不过修复起来很简单:

public class ConsoleWriter
{
    private static object _MessageLock= new object();

    public void WriteMessage(string message)
    {
        lock (_MessageLock)
        {
            Console.BackgroundColor = ConsoleColor.Red;
            Console.WriteLine(message);
            Console.ResetColor();
        }
    }
}

我开发了一个名为cConsole的有趣的小类库,用于彩色控制台输出。 使用示例:

const string tom = "Tom";
const string jerry = "Jerry";
CConsole.WriteLine($"Hello {tom:red} and {jerry:green}");

它使用c# FormattableString, IFormatProvider和ICustomFormatter接口的一些功能来设置文本切片的前景和背景颜色。 你可以在这里看到cConsole的源代码

只是补充上面的答案,所有使用控制台。要改变同一行文本的颜色,可以这样写:

Console.Write("This test ");
Console.BackgroundColor = bTestSuccess ? ConsoleColor.DarkGreen : ConsoleColor.Red;
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine((bTestSuccess ? "PASSED" : "FAILED"));
Console.ResetColor();

是的,可能如下所示。这些颜色可以在控制台应用程序中使用,以红色等方式查看一些错误。

Console.BackgroundColor = ConsoleColor.Blue;
Console.ForegroundColor = ConsoleColor.White;//after this line every text will be white on blue background
Console.WriteLine("White on blue.");
Console.WriteLine("Another line.");
Console.ResetColor();//reset to the defoult colour