简化if-else表达式

时间:2018-11-05 14:22:42

标签: c#

我正在尝试在if ... else中管理3结果对话框,但是我发现它很难使用。这是我的代码:

if (MessageBox.Show("Are you sure you want to exit", "", MessageBoxButtons.YesNoCancel) == DialogResult.Yes) {
   MessageBox.Show("Why?!", "", MessageBoxButtons.RetryCancel);
   Application.Restart();
} else if (MessageBox.Show("Are you sure you want to exit", "", MessageBoxButtons.YesNoCancel) == DialogResult.No) {
    if (MessageBox.Show("OK ^_^! Good Luck!", "", MessageBoxButtons.OK) == DialogResult.OK) 
        Application.Restart();
} else {
    if (MessageBox.Show("Are you sure you want to cancel?", "", MessageBoxButtons.OKCancel) == DialogResult.OK) {
        MessageBox.Show("Ok! Good Luck!");
        Application.Restart();
    } else {
        MessageBox.Show("Error!");
        Application.Restart();
    }
}

每当我运行它时,如果我按“否”或“取消”,它将打开一个新对话框。我该如何避免呢?

2 个答案:

答案 0 :(得分:7)

您应该首先获取DialogResult,然后在if-else语句中使用它:

DialogResult result = MessageBox.Show("Are you sure you want to exit", "", MessageBoxButtons.YesNoCancel);

if(result == DialogResult.Yes)
{
    //Code if Ok
}
else if(result == DialogResult.No)
{
    //Code if No
}
else
{
    //Code if Cancel
}

这样MessageBox只会打开一次

答案 1 :(得分:3)

您的第一个if语句正在检查Yes的结果:

if (MessageBox.Show("Are you sure you want to exit", "", MessageBoxButtons.YesNoCancel) == DialogResult.Yes) 

如果用户选择NoCancel,则移至下一个产生另一个if的{​​{1}}语句:

MessageBox

最后,如果用户选择“取消”,您将获得另一个else if (MessageBox.Show("Are you sure you want to exit", "", MessageBoxButtons.YesNoCancel) == DialogResult.No) {

MessageBox

这就是为什么您看到多个else { if (MessageBox.Show("Are you sure you want to cancel?", "", MessageBoxButtons.OKCancel) == DialogResult.OK) //Other code here... } 实例的原因。

因此,您应该只显示一个框,然后使用结果。但是,该代码建议必须在某些实例上收集其他信息:

MessageBox

我不认为您的代码应该在var result = MessageBox.Show("Are you sure you want to exit", "", MessageBoxButtons.YesNoCancel); switch(result) { case DialogResult.Yes: //Another box pops up to ask the user why MessageBox.Show("Why?!", "", MessageBoxButtons.RetryCancel); Application.Restart(); break; case DialogResult.No: //Informational box MessageBox.Show("OK ^_^! Good Luck!", "", MessageBoxButtons.OK); Application.Restart(); default: //Assume Cancel to be the default behavior, //Pick any value to be the default. It's up to you. //Make sure they really, REALLY want to cancel if (MessageBox.Show("Are you sure you want to cancel?", "", MessageBoxButtons.OKCancel) == DialogResult.OK) { MessageBox.Show("Ok! Good Luck!"); Application.Restart(); } else { MessageBox.Show("Error!"); Application.Restart(); } } 替代方案的Application.Restart分支上调用false,但是逻辑取决于您。

正如其他人指出的那样,请尝试正确缩进/格式化您的代码。它将使您和其他人更容易理解。