【发布时间】:2015-02-06 01:08:14
【问题描述】:
我有一个 Visual Studio C# WinForms 应用程序,其中必须计算一个布尔值以确定程序接下来要做什么,
要么抛出一个消息框,要么执行一个函数。问题是当布尔值评估为
是的。
代码如下:
private void btnNextQuestion_Click(object sender, EventArgs e)
{
if (QuestionNeedsSaving == true)
{
QuestionNeedsSaving = false;
MessageBox.Show("You have made changes to this question." + "\r\n" + "\r\n" + "Click the Update Question button to " + "\r\n" + "Save changes or the changes will be lost.", "OOPS!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
else if (QuestionNeedsSaving == false)
GoToNextQuestion();
}
如果布尔值“QuestionNeedsSaving”为真,则它被设置为假并抛出一个消息框。 否则,如果“QuestionNeedsSaving”为假,则调用“GoToNextQuestion”函数。
问题在于,如果“QuestionNeedsSaving”为真,则消息框和“GoToNextQuestion”都会被执行。
“GoToNextQuestion”只有在“QuestionNeedsSaving”一开始就为假时才应该执行。
【问题讨论】:
-
听起来该方法被调用了两次。设置断点并使用 Visual Studio 单步执行。
-
代码没问题,错误应该在此处未显示的部分 - 即按钮单击的双重注册。