【发布时间】:2019-05-13 09:38:30
【问题描述】:
我这里有一个代码,它从数组中随机选择一个字符串,然后使用相应的字符串来更改背景的颜色。前景也是如此,但是代码很多,如果我想添加更多颜色,那将非常耗时。 有小费吗?
代码如下:
static void Main(string[] args)
{
Random random = new Random();
Console.WriteLine("Input your name: ");
string yourName = Console.ReadLine();
while (true)
{
string[] colours = new string[5] {"red" , "white", "yellow" , "magenta" , "blue" };
int backColour = random.Next(0,5);
if (backColour == 0)
{
Console.BackgroundColor = ConsoleColor.Red;
}
if (backColour == 1)
{
Console.BackgroundColor = ConsoleColor.White;
}
if (backColour == 2)
{
Console.BackgroundColor = ConsoleColor.Yellow;
}
if (backColour == 3)
{
Console.BackgroundColor = ConsoleColor.Magenta;
}
if (backColour == 4)
{
Console.BackgroundColor = ConsoleColor.Blue;
}
int frontColour = random.Next(0, 5);
if (frontColour == 0)
{
Console.ForegroundColor = ConsoleColor.Red;
}
if (frontColour == 1)
{
Console.ForegroundColor = ConsoleColor.White;
}
if (frontColour == 2)
{
Console.ForegroundColor = ConsoleColor.Yellow;
}
if (frontColour == 3)
{
Console.ForegroundColor = ConsoleColor.Magenta;
}
if (frontColour == 4)
{
Console.ForegroundColor = ConsoleColor.Blue;
}
Console.Write("All work and no pla`enter code here`y makes " + yourName + " a dull person! ");
Console.Clear();
}
}
非常感谢!
【问题讨论】:
-
您的目标是什么:Winforms、WPF、ASP..?您应该始终正确标记您的问题,以便人们可以在问题页面上看到它!
-
我建议分别随机选择红色、绿色、蓝色分量,即 0 到 255 并将它们组合成颜色。
-
只需将颜色对象放在一个数组中并循环遍历数组,每个索引都有不同的颜色。您可以随时在数组中添加或删除颜色,而无需更改循环代码。
-
前后颜色可以一样吗?
-
刚刚注意到 - 您的
while循环似乎关闭了,因为您将获得永久更改颜色的迪斯科模式 - 您的Console.ReadLine()可能应该在while循环内以使循环停止并等待进一步的输入 - 你应该有一些退出代码来避免无限循环。
标签: c# random colors console-application