如何选择随机颜色组合

本文关键字:随机 颜色 组合 选择 何选择 | 更新日期: 2023-09-27 18:07:10

目标:我想从一个数组中随机抓取两个字符串,然后把它们放在一起。

问题:当我点击button1时,textbox1显示一个背靠背的颜色

(BlackBlack、BlueBlue、BrownBrown、GrayGray、GreenGreen)缺席

而不是显示两种不同的颜色。

(BlackBlue, BlueBrown, BrownGray, GrayGreen, GreenOrange)☑

这是我目前的代码:

        string[] Colors = { "Black", "Blue", "Brown", "Gray", "Green", "Orange", "Pink", "Purple", "Red", "White", "Yellow" };
    private void button1_Click(object sender, EventArgs e)
    {
        string FirstColor;
        string SecondColor;
        FirstColor = Colors[new Random().Next(0, Colors.Length)];
        SecondColor = Colors[new Random().Next(0, Colors.Length)];
        textBox1.Text = FirstColor + SecondColor;
    }

如何选择随机颜色组合

 string[] Colors = { "Black", "Blue", "Brown", "Gray", "Green", "Orange", "Pink", "Purple", "Red", "White", "Yellow" };
    private Random random = new Random();
    private void button1_Click(object sender, EventArgs e)
    {
        string FirstColor;
        string SecondColor;
        FirstColor = Colors[random.Next(0, Colors.Length)];          
        do
        {
            SecondColor = Colors[random.Next(0, Colors.Length)];
        } while (!FirstColor.Equals(SecondColor));
        textBox1.Text = FirstColor + SecondColor;
    }

随机数生成器在创建时由当前时间戳播种。如果你连续创建两个,它们将具有相同的种子。而是创建一个,将它存储在一个字段中,然后重用它。

string[] Colors = { "Black", "Blue", "Brown", "Gray", "Green", "Orange", "Pink", "Purple", "Red", "White", "Yellow" };
private Random random = new Random();
private void button1_Click(object sender, EventArgs e)
{
    string FirstColor;
    string SecondColor;
    FirstColor = Colors[random.Next(0, Colors.Length)];
    SecondColor = Colors[random.Next(0, Colors.Length)];
    textBox1.Text = FirstColor + SecondColor;
}