3 回答
TA贡献1775条经验 获得超11个赞
这是我会使用的,可能不是最好的方法,但它确实有效。
class Program
{
static void Main(string[] args)
{
// ~ red, ` green, ^ blue, * yellow, _ purple
ColorWrite("~M`u^l*t_i", true);
ColorWrite("~This is red,^ yet this is blue.", true);
ColorWrite("~Mul`ti^ple ", false);
ColorWrite("*Col_ours ", false);
}
// variable contains both consoleColor and char
struct ColourKey
{
public ConsoleColor color;
public char key;
public ColourKey(ConsoleColor Color, char Key)
{
this.color = Color;
this.key = Key;
}
}
static void ColorWrite(string rawtext, bool endline)
{
//all avaliable colours, for more just make the array bigger
ColourKey[] Pallete = new ColourKey[5];
Pallete[0] = new ColourKey(ConsoleColor.Red, '~');
Pallete[1] = new ColourKey(ConsoleColor.Green, '`');
Pallete[2] = new ColourKey(ConsoleColor.Blue, '^');
Pallete[3] = new ColourKey(ConsoleColor.Yellow, '*');
Pallete[4] = new ColourKey(ConsoleColor.DarkMagenta, '_'); //ConsoleColor does not contain purple
foreach (char c in rawtext)
{
bool CanWrite = true;
foreach (ColourKey ck in Pallete)
{
if (c == ck.key)
{
Console.ForegroundColor = ck.color;
CanWrite = false;
}
}
if (CanWrite)
{
Console.Write(c);
}
}
Console.ResetColor();
// true function works like writeline(), false works like write()
if (endline)
{
Console.WriteLine();
}
}
TA贡献1790条经验 获得超9个赞
您可以使用如下代码所示的字典,然后使用循环:
Dictionary<int, KeyValuePair<string, ConsoleColor>> keyValuePairs = new Dictionary<int, KeyValuePair<string, ConsoleColor>>();
keyValuePairs.Add(1, new KeyValuePair<string, ConsoleColor>("my blue text", ConsoleColor.Blue));
keyValuePairs.Add(2, new KeyValuePair<string, ConsoleColor>("my red text", ConsoleColor.Red));
foreach (var keyItem in keyValuePairs.Keys)
{
ConsoleColor color = keyValuePairs[keyItem].Value;
string textTobeDisplayed = keyValuePairs[keyItem].Key;
Console.ForegroundColor = color;
Console.Write(textTobeDisplayed);
}
TA贡献1842条经验 获得超12个赞
我希望这对你有帮助
class Program
{
static void Main(string[] args)
{
Console.ForegroundColor = ConsoleColor.Blue;
Console.Write("White on Blue.");
Console.ForegroundColor = ConsoleColor.Red;
Console.Write("White on Red.");
Console.ResetColor();
Console.ReadLine();
}
}
- 3 回答
- 0 关注
- 145 浏览
添加回答
举报