如何选择随机颜色组合

时间:2015-08-10 05:21:35

标签: c#

目标:我想随机从数组中获取2个字符串,然后将它们组合在一起。

问题:当我点击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;
    }

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

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

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