som*_*ing 3 c# syntax if-statement

为什么这样做?
private void button1_Click(object sender, EventArgs e)
{
if (!checkBox1.Checked)
{
MessageBox.Show("The box is not checked!");
}
if (checkBox1.Checked == true)
{
if (label1.BackColor == Color.Red)
{
label1.BackColor = Color.Blue;
}
else
{
label1.BackColor = Color.Red;
}
}
}
Run Code Online (Sandbox Code Playgroud)
但这不是吗?
private void button1_Click(object sender, EventArgs e)
{
if (!checkBox1.Checked)
{
MessageBox.Show("The box is not checked!");
}
if (checkBox1.Checked == true)
{
if (label1.BackColor == Color.Red)
{
label1.BackColor = Color.Blue;
}
if (label1.BackColor == Color.Blue)
{
label1.BackColor = Color.Red;
}
}
}
Run Code Online (Sandbox Code Playgroud)
我认为compliler会在每次按下按钮时读取行,所以在彼此之后有两个if语句不应该有任何不同.
如果是红色,则变为蓝色,如果是蓝色,则将其更改为红色.首先,如果首先if将其更改为蓝色,则第二个if将其更改为红色.它以这种方式工作,因为指令是按顺序执行的,所以if在第一次执行后总会检查第二个指令if.只是使用else if,if如果第一个被解雇,第二个将无法工作:
// if red then change to blue
if (label1.BackColor == Color.Red)
{
label1.BackColor = Color.Blue;
}
// otherwise, if blue then change to red
// this condition will be checked if first "if" was false
else if (label1.BackColor == Color.Blue)
{
label1.BackColor = Color.Red;
}
Run Code Online (Sandbox Code Playgroud)