我有一个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”为true,则将其设置为false并抛出一个消息框。 否则,如果“QuestionNeedsSaving”为false,则调用函数“GoToNextQuestion”。
问题是如果“QuestionNeedsSaving”为真,则执行消息框AND“GoToNextQuestion”。
“GoToNextQuestion”只应在“QuestionNeedsSaving”为假的情况下执行。
答案 0 :(得分:0)
实际上主要的问题是QuestionNeedsSaving的常量状态,它总是通过if条件进行,并且更好地在其他地方做出QuestionNeedsSaving值的决定:
private void btnNextQuestion_Click(object sender, EventArgs e)
{
if (QuestionNeedsSaving == true)
{
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();
}
答案 1 :(得分:0)
只需运行此代码,您就会知道在奇数按钮的情况下单击QuestionNeedSaving = true会给出Next Question消息,但是如果按钮单击,则单击QuestionNeedSaving = false来给出OOPS!消息,将永远不会相同。
using System;
using System.Drawing;
using System.Windows.Forms;
namespace boolDecission
{
public partial class Form1 : Form
{
bool QuestionNeedsSaving = false;
int x = 0;
public Form1()
{
InitializeComponent();
}
private void btnNextQuestion_Click(object sender, EventArgs e)
{
x = x + 1;
//even number will make QuestionNeedsSaving = false and odd number will make QuestionNeedsSaving = true.
if (x % 2 == 1)
{
QuestionNeedsSaving = false;
}
else
{
QuestionNeedsSaving = true;
}
if (QuestionNeedsSaving == true)
{
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();
}
}
public void GoToNextQuestion()
{
MessageBox.Show("Next Question");
}
}
}