我目前正在尝试更改数组的背景颜色,特别是在这种情况下,grid[0, 0]。我四处寻找了一段时间,似乎什么也想不出来。这可能是一个非常简单的问题,或者我需要休息一下!
Console.BackgroundColor(grid[0,0]) = ConsoleColor.Cyan;
我正在尝试使背景颜色为青色。变量是一个字符串,包含一个空格。
提前干杯。
完整来源:
static void Main(string[] args)
{
Console.CursorSize = 100;
int row, col;
string[,] grid = new string[10, 10];
for (col = 0; col < 10; col++)
{
for (row = 0; row < 10; row++)
{
grid[col, row] = " ";
}
}
for (col = 0; col < 10; col++)
{
for (row = 0; row < 10; row++)
{
Console.Write(grid[col, row]);
}
Console.Write("n");
}
Console.BackgroundColor(grid[0,0]) = ConsoleColor.Cyan;
Console.ReadKey();
}
好的,您需要做的第一件事是制作可以同时包含颜色和字符串的类型grid
。
public class ColoredString
{
public ConsoleColor Color{get; set;}
public string Content {get; set;}
}
然后,当你设置颜色时,这样做。
grid[0,0].Color = ConsoleColor.Cyan;
之后,您可以像这样打印彩色
public static void PrintColor(ColoredString str)
{
var prevColor = Console.BackgroundColor;
Console.BackgroundColor = str.Color;
Console.Write(str.Content);
Console.BackgroundColor = prevColor;
}
这是一个SSCCE
public class Program
{
static void Main(string[] args)
{
var str = new ColoredString()
{
Color = ConsoleColor.Cyan,
Content = "abcdef",
};
PrintColor(str);
Console.ReadKey(false);
}
public static void PrintColor(ColoredString str)
{
var prevColor = Console.BackgroundColor;
Console.BackgroundColor = str.Color;
Console.Write(str.Content);
Console.BackgroundColor = prevColor;
}
}
public class ColoredString
{
public ConsoleColor Color { get; set; }
public string Content { get; set; }
}
我很确定Console.BackgroundColor设置了要打印的文本的颜色。因此,如果要打印带有另一种颜色的一个单词的字符串,则可以执行以下操作:
Console.Write("Hello word, the following text is cyan: ");
Console.BackgroundColor = ConsoleColor.Cyan;
Console.Write("Cyan text ");
Console.BackgroundColor = ConsoleColor.Black;
Console.WriteLine("(but this is not cyan)");