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

标签 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");
}

我主要想关注这段代码...以缩短...:)

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

最佳答案

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

while(Turn==2 && buttons.Any(b => b.Text == ""))

一般来说,有 9 个按钮,它们可能应该位于数组或列表中,以便更简单地访问:

Button[] buttons = new Button[] {button1, button2, button3, ... } ;

然后您可以通过 buttons[0] 而不是 button1 等方式访问它。

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

关于C# 如何缩短这个超长的重载 do while 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14533147/

相关文章:

c# - 我需要更改asp :Login control button的样式和控件使用

c# - 如何在调试应用程序期间定义事务超时

c# - 使用 C# 以单一形式动态创建多个文本框?

时间:2018-01-08 标签:c#winforms: determine first run of program

asp.net - 开源开发过程中如何混淆数据库认证信息?

c++ - 我的数组在 C++ Visual Studio 中仅显示 300 个元素

c# - 主构造函数不再在 VS2015 中编译

c# - 生成 Swagger.json 文件后如何以编程方式访问它

c# - TabPage.Hide() 是做什么的?

.net - 如何手动创建一个 mdf 文件供 localdb 使用?