如果是C#中的/ else语句 [英] If / else statements in C#

查看:156
本文介绍了如果是C#中的/ else语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这项工作?

    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;
            }
        }
    }

但这不是吗?

   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;
            }
        }
    }

我认为compliler每次按下按钮都会读取这些行,所以在两个if语句之后不应该有任何不同。

I would think that the compliler would read the lines each time I press the button so it should not be any different to have two if statements after each other.

推荐答案

如果它是红色,则会变为蓝色,然后如果它是蓝色,则将其更改为红色。基本上首先如果如果将其更改为蓝色,则第二个如果将其更改为红色。它的工作方式是这样的,因为指令是按顺序执行的,所以在你的第一个 if 之后总是检查你的第二个 if 。只需使用 else,如果那么第二个如果在第一个被解雇时不起作用:

You are changing to blue if it was red and then your are changing it to red if it was blue. Basically first if first if will change it to blue then second if will change it back to red. It works this way because instructions are executed sequentially, so your second if is always checked after your first if. Just use else if so second if won't work if first one fired:

// 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;
}

这篇关于如果是C#中的/ else语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆