在C#中随机更改前景和背景的颜色

时间:2018-12-12 09:57:49

标签: c# random colors console-application

我这里有一个代码,可以从数组中随机选择一个字符串,然后使用该字符串更改背景色。对于前景也是如此,但是有很多代码,如果我想添加更多颜色,那将非常耗时。 有小费吗?

这是代码:

 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();
                }
        }

非常感谢!

1 个答案:

答案 0 :(得分:3)

直接选择颜色而不是int -> string[] -> color

ConsoleColor[] colours = { ConsoleColor.Red, 
                           ConsoleColor.White, 
                           ConsoleColor.Yellow, 
                           ConsoleColor.Magenta, 
                           ConsoleColor.Blue };
Console.BackgroundColor = colours[random.Next(0, colours.Length)];
Console.ForegroundColor = colours[random.Next(0, colours.Length)];