3

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

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

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

4

2 回答 2

7
// 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);         
} 
于 2012-06-09T02:16:52.153 回答
3

如果要使用标准控制台颜色,可以混合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);
}
于 2012-06-09T02:20:54.773 回答