所以我在c#中乱搞,并想知道如何从数组中生成我的字符串,但是使用随机颜色:
while (true)
{
string[] x = new string[] { "", "", "" };
Random name = new Random();
Console.WriteLine((x[name.Next(3)]));
Thread.Sleep(100);
}
当我输出x时,我希望它是随机颜色。 感谢
答案 0 :(得分: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);
}
答案 1 :(得分:4)
如果您想使用标准控制台颜色,可以混合ConsoleColor Enumeration和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);
}