C#如何缩短这个长的重载do while语句

Gle*_*ter 2 c# winforms visual-studio-2012

我做了一个井字游戏,并且我正在用更少的代码制作另一个版本。无论如何...这是我的代码...我已经在do while语句之间使用了一些代码,但是是的...

    var rc = new Random();
    do
    {
        storeRI = rc.Next(1, 9);

        if (storeRI == 1 & button1.Text == "")
        {
            button1.Text = "O";
            Turn = 1;
            TestWin();
            break;
        }
        else if (storeRI == 2 & button2.Text == "")
        {
            button2.Text = "O";
            Turn = 1;
            TestWin();
            break;
        }


    } while (Turn == 2 & button1.Text == "" | button2.Text == "" | button3.Text == "" | button3.Text == "" | button4.Text == "" | button5.Text == "" | button6.Text == "" | button7.Text == "" | button8.Text == "" | button9.Text == "");
}
else
{
    MessageBox.Show("It's a draw");
}
Run Code Online (Sandbox Code Playgroud)

我主要想专注于这段代码...缩短时间... :)

 } while (Turn == 2 & button1.Text == "" | button2.Text == "" | button3.Text == "" | button3.Text == "" | button4.Text == "" | button5.Text == "" | button6.Text == "" | button7.Text == "" | button8.Text == "" | button9.Text == "");
Run Code Online (Sandbox Code Playgroud)

D S*_*ley 5

从您的各个按钮创建按钮列表,然后将其更改为

while(Turn==2 && buttons.Any(b => b.Text == ""))
Run Code Online (Sandbox Code Playgroud)

通常,使用9个按钮,它们可能应该位于数组或列表中,以简化访问:

Button[] buttons = new Button[] {button1, button2, button3, ... } ;
Run Code Online (Sandbox Code Playgroud)

那么您可以访问buttons[0]而不是button1,等等。

我会在您的Form初始值设定项中执行此操作,而不是使用按需执行此功能的函数。