简体   繁体   English

C# 是否有理由不支持逻辑评估中的简写、空条件检查?

[英]Is there a reason C# doesn't support short-hand, null-conditional checking in logical evaluations?

I'm often finding myself writing code that checks for null prior to checking a property for a value.我经常发现自己编写的代码在检查属性的值之前检查null The simplest form of this would be:最简单的形式是:

if (someInstance != null && someInstance.SomeBooleanProperty)

Is there a reason we can't use the null-conditional operator ( ?. ) to simplify that check if the property following it is a boolean like this?我们是否有理由不能使用空条件运算符 ( ?. ) 来简化检查它后面的属性是否是这样的布尔值?

if (someInstance?.SomeBooleanProperty)

The above example won't compile because it evaluates to null , not to true or false , hence you get an error saying there's no implicit cast available for bool?上面的示例无法编译,因为它的计算结果为null ,而不是truefalse ,因此您会收到错误消息,说没有可用于bool?隐式bool? to bool . bool

We could always cast, or directly check for a value, such as:我们总是可以强制转换,或者直接检查一个值,例如:

if (someInstance?.SomeBooleanProperty == false)

That works fine, and in all honesty, it's not exactly that much extra code.这工作得很好,老实说,它并没有那么多额外的代码。 Just, in my opninion here, with all of the simplifications C# has introduced over the years, I can't help but wonder if there is a reason we still can't utilize a shorthand null conditional like this?只是,在我看来,随着 C# 多年来引入的所有简化,我不禁想知道我们是否仍然不能使用像这样的简写 null 条件?

I think the inherent problem with just using a ?.我认为仅使用?.的固有问题?. alone is what does the condition evaluate to when someInstance is null.someInstance为 null 时,条件评估结果是什么。 This is why the compiler complains and why you need the null check condition and the non null boolean evaluation.这就是编译器抱怨的原因以及您需要空检查条件和非空布尔评估的原因。 The someInstance?.SomeBooleanProperty ?? false someInstance?.SomeBooleanProperty ?? false someInstance?.SomeBooleanProperty ?? false would satisfy both conditions. someInstance?.SomeBooleanProperty ?? false将满足这两个条件。 ?. alone cannot / shoudn't infer this logic.单独不能/不应该推断出这个逻辑。

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

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