我需要通过方法对字符串进行着色,所以我使用Console.ForegroundColor
属性并稍后编写文本,但是我在某个地方犯了一个错误,所以所有行都是一种颜色。还是有更好的解决方案?我需要通过 &0-&f (十六进制)对字符串进行着色并将其输出到控制台,这是我的解决方案:
public static void ColorizeConsoleMessage(string message)
{
var matches = Regex.Matches(message, "&+[0-9a-f]");
var split = Regex.Split(message, "&+[0-9a-f]");
var def = Console.ForegroundColor;
var i = 0;
foreach (var match in matches)
{
switch (match.ToString().Replace("&", "").ToCharArray()[0])
{
case '0':
Console.ForegroundColor = ConsoleColor.White;
break;
case '1':
Console.ForegroundColor = ConsoleColor.Gray;
break;
case '2':
Console.ForegroundColor = ConsoleColor.DarkGray;
break;
case '3':
Console.ForegroundColor = ConsoleColor.Black;
break;
case '4':
Console.ForegroundColor = ConsoleColor.Red;
break;
case '5':
Console.ForegroundColor = ConsoleColor.Green;
break;
case '6':
Console.ForegroundColor = ConsoleColor.Blue;
break;
case '7':
Console.ForegroundColor = ConsoleColor.Yellow;
break;
default:
Console.ForegroundColor = ConsoleColor.White;
break;
}
Console.Write(split[i]);
i++;
}
Console.WriteLine();
Console.ForegroundColor = def;
}
并测试:EventManager.ColorizeConsoleMessage("&4Hello, &6world!");