无法在条件语句中使用逻辑运算符

时间:2018-04-16 14:56:58

标签: c# conditional-statements operator-keyword logical-operators

我正在尝试编写一个条件语句,该语句将在单击按钮时进行检查,以检查是否至少选中了一个复选框。 所以一个例子是:

if (
    checkbox_delete.Checked = false && 
    checkbox_export = false && 
    checkbox_name = false && 
    checkbox_PST = false
)
{
    string messageboxtext = "Please check at least one of the checkboxes.";
    MessageBox.Show(messageboxtext);
}

我收到错误消息说: 运营商&&'不能应用于'bool'和'System.Windows.Forms.CheckBox'类型的操作数 谁能帮助弄清楚我做错了什么?

聚苯乙烯。我也尝试过做

 if (
    (checkbox_delete.Checked = false) && 
    (checkbox_export = false) && 
    (checkbox_name = false) && 
    (checkbox_PST = false)
 )
 {
     string messageboxtext = "Please check at least one of the checkboxes.";
     MessageBox.Show(messageboxtext);
 }

但我接着说:

  

无法将类型'bool'隐式转换为'System.Windows.Forms.CheckBox'

1 个答案:

答案 0 :(得分:2)

您当前的代码存在一些问题:

  1. 正如您所发现的,您需要引用属性Checked。有关相关文档,请参阅https://msdn.microsoft.com/en-us/library/system.windows.forms.checkbox.checked(v=vs.110).aspx

  2. 此外,您应该使用=而不是==。第一个用于分配;第二个是平等比较。有关此点的详细信息,请参阅https://stackoverflow.com/a/4704401/361842。尝试在控制台应用程序或LinqPad中运行以下代码,以查看在被误解时可以得到的一些奇怪结果:

  3. 问题示例

    bool something = true;
    Debug.WriteLine(something); //returns true
    if (something = false) {
        Debug.WriteLine("this won't show");
    } else {
        Debug.WriteLine("this will show");  //this is output, which you'd maybe expect, but for the wrong reasons... 
    }
    Debug.WriteLine(something); //returns false, as we've reassigned it accidentally above
    
    if (something = false) {
        Debug.WriteLine("this won't run");
    } else {
        Debug.WriteLine("surprise!"); //even though we saw above that something is now false, because we assign the value false to something and then evaluate the value of something (rather than comparing `something` with `false`, finding them equanlt and thus returning `true`; so the above statement effectively reads `if (false)`
    }
    

    输出:

    True
    this will show
    False
    surprise!
    

    ...除此之外,您当前的代码也会取消选中所有复选框,因为您将checked属性设置为false。

    修改后的代码:

    if (
        checkbox_delete.Checked == false && 
        checkbox_export.Checked  == false && 
        checkbox_name.Checked  == false && 
        checkbox_PST.Checked  == false
    )
    {
        string messageboxtext = "Please check at least one of the checkboxes.";
        MessageBox.Show(messageboxtext);
    }
    

    另一种说“如果一切都是假”的方法就是说“如果都不是真的”。您可能会发现更容易阅读;但这取决于个人喜好。请参阅下面的示例:

    if (!(
        checkbox_delete.Checked || 
        checkbox_export.Checked || 
        checkbox_name.Checked || 
        checkbox_PST.Checked 
    ))
    {
        string messageboxtext = "Please check at least one of the checkboxes.";
        MessageBox.Show(messageboxtext);
    }