无状态声明

Declaration without state

您好,我有简单的代码,想要一键控制标签:

private void button1_Click(object sender, EventArgs e)
{            
    bool T=true;

    if (T)
    {
        label1.Text = "GOOD";
        T=false;
    }
    else if(!T){
        label1.Text = "BAD";
        T=true;
    }
}

问题是每次我按下按钮时它都声明为 true 并且每次都是 true 条件。我不能这样声明

bool T;

因为出现错误:

CS0165 Use of unassigned local variable 'T' WindowsFormsApp1

如何申报一次?

当你想在某些单击状态和未单击状态之间切换时,你需要 class 中的成员,而不是仅存在于 方法:

class MyClass
{
    bool foo;

    private void button1_Click(object sender, EventArgs e)
    {            
        if (this.foo)
        {
            label1.Text = "GOOD";
            this.foo=false;
        }
        else
        {
            label1.Text = "BAD";
            this.foo = true;
        }
    }
}

另请注意,我省略了 else if,因为布尔值只能有两种状态:truefalse。没有第三个条件。因此,匹配第一个条件的所有内容将自动匹配第二个条件,您不需要(再次)测试布尔值。

如果您想将 label1.TextGOOD 切换到 BAD,您可以尝试一个简单的旋转运算符:

private void button1_Click(object sender, EventArgs e)
{            
    label1.Text = string.Equals("GOOD", label1.Text, StringComparison.OrdinalIgnoreCase)
      ? "BAD"
      : "GOOD";
}

如果您想要更详细的解决方案,让我们提取一个属性,例如:

public bool IsGood {
  get {
    // Simplest implementation; often adding a backing field is a good idea
    return label1.Text = string
      .Equals("GOOD", label1.Text, StringComparison.OrdinalIgnoreCase);
  }
  set {
    label1.Text = value ? "GOOD" : "BAD";
  }
}

然后点击事件

 private void button1_Click(object sender, EventArgs e) {
   IsGood = !IsGood; 
 }