简体   繁体   English

为什么这段代码似乎出现了错误?

[英]Why does this code seem to exhibit a bug?

I've got a CanExecute for a WPF command that seems to work differently depending on how explicit I am with the compiler; 我有一个针对WPF命令的CanExecute ,它看起来有所不同,具体取决于我对编译器的明确程度; the problem is, I wouldn't expect to have to be explicit. 问题是,我不希望必须明确。

private bool CanRemoveField()
{
    return SelectedField != null &&
        Context.Item.Id == 0
        ? _fieldsByFieldModel.ContainsKey(SelectedField)
        : !_hasAnyCosts;
}

The above code, when queried for an Item where Id != 0 holds true, the button is enabled despite SelectedField being null , so I'd expect the conditional to short out and return false . 上面的代码,当查询一个项目,其中Id != 0成立时, 尽管 SelectedFieldnull ,按钮仍然启用,所以我希望条件为short并返回false

The code tweaked slightly: 代码略有调整:

private bool CanRemoveField()
{
    return SelectedField != null &&
        (Context.Item.Id == 0
        ? _fieldsByFieldModel.ContainsKey(SelectedField)
        : !_hasAnyCosts);
}

I've introduced some parentheses around the ternary if, and this now exhibits the desired behaviour of disabling the button when no field is selected. 我已经在三元组周围引入了一些括号,并且现在显示了在没有选择字段时禁用按钮的所需行为。

Given the fact it's a ternary if, I'd have expected the behaviour I wanted to be possible without the need for parentheses as it should just be seen as one statement, no? 鉴于它是一个三元组,如果,我已经预料到我想要的行为,而不需要括号,因为它应该只被视为一个陈述,不是吗?

Because of operator precedence, your first example is equivalent to: 由于运算符优先级,您的第一个示例等效于:

private bool CanRemoveField()
  {
    return (SelectedField != null &&
        Context.Item.Id == 0)
        ? _fieldsByFieldModel.ContainsKey(SelectedField)
        : !_hasAnyCosts;
  }

The results you're seeing make sense, since the && logical-and operator has a higher precedence than the ? : 你看到的结果是有意义的,因为&& logical-and运算符的优先级高于? : ? : conditional expression . ? :条件表达式

So your first code snippet is essentially: 所以你的第一个代码片段基本上是:

return (SelectedField != null && Context.Item.Id == 0)
    ? _fieldsByFieldModel.ContainsKey(SelectedField)
    : !_hasAnyCosts;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM