如何生成随机颜色

本文关键字:生成随机颜色 | 更新日期: 2023-09-27 18:36:34

所以我在 c# 中乱搞,想知道如何从数组生成我的字符串,但颜色是随机的:

    while (true)
        {
            string[] x = new string[] { "", "", "" };
            Random name = new Random();
            Console.WriteLine((x[name.Next(3)]));
            Thread.Sleep(100);
        }

当我输出 x 时,我希望它是随机颜色。谢谢

如何生成随机颜色

// Your array should be declared outside of the loop
string[] x = new string[] { "", "", "" }; 
Random random = new Random();     
// Also you should NEVER have an endless loop ;)
while (true)         
{            
     Console.ForegroundColor = Color.FromArgb(random.Next(255), random.Next(255), random.Next(255));
     Console.WriteLine((x[random.Next(x.Length)]));             
     Thread.Sleep(100);         
} 

如果要使用标准控制台颜色,可以混合使用 ConsoleColor 枚举和 Enum.GetNames() 来获取随机颜色。 然后,您可以使用 Console.ForegroundColor 和/或 Console.BackgroundColor 来更改控制台的颜色。

// Store these as static variables; they will never be changing
String[] colorNames = ConsoleColor.GetNames(typeof(ConsoleColor));
int numColors = colorNames.Length;
// ...
Random rand = new Random(); // No need to create a new one for each iteration.
string[] x = new string[] { "", "", "" };
while(true) // This should probably be based on some condition, rather than 'true'
{
    // Get random ConsoleColor string
    string colorName = colorNames[rand.Next(numColors)];
    // Get ConsoleColor from string name
    ConsoleColor color = (ConsoleColor) Enum.Parse(typeof(ConsoleColor), colorName);
    // Assuming you want to set the Foreground here, not the Background
    Console.ForegroundColor = color;
    Console.WriteLine((x[rand.Next(x.Length)]));
    Thread.Sleep(100);
}