“获取随机”按钮

本文关键字:按钮 获取随机 随机 获取 | 更新日期: 2023-09-27 18:26:56

我有1-2-3…12按钮,我想随机获得其中4个(不重复),然后给它们一个单一的颜色,例如红色。我该怎么做?

    public Form1()
    {
        InitializeComponent();
        Button[] LeftArr = new Button[12] { button1, button2, button3, button4, button5, button6, button7, button8, button9, button10, button11, button12 };
        int i = 0;
        for (i = 0; i <= LeftArr.Length; i++)
        {
            Random rnd = new Random();
            Button ShipHere = rnd.Next( button1, button12 );
           // this is where i'm stuck
        }

“获取随机”按钮

首先,您需要确保不会在循环中的每次迭代中都创建新的Random对象。否则,您将得到重复项。

Random rnd = new Random();
List<Button> randomButtons = new List<Button>(4);
for (int i = 0;i < 4;++i)
{
    Button chosenButton;
    // Keep looping until we get a button we haven't already picked
    do
    {
        chosenButton = LeftArr[rnd.Next(0, LeftArr.Length)];
    } while (randomButtons.Contains(chosenButton));
    randomButtons.Add(chosenButton);
}
foreach (Button button in randomButtons)
    button.BackColor = Color.Red;