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
[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}");