简体   繁体   English

在if语句(C#)中使用空合并运算符

[英]using null-coalescing operator inside if statement (C#)

I know null-coalescing operator returns the left hand operand if it is not null, but I hadn't seen anyone using it in an if-statement like: 我知道null算术运算符如果不为null则返回左手操作数,但是我没有看到任何人在if语句中使用它,例如:

if (car.IsSold ?? false)
 ...

I'm guessing it means if car.IsSold is not null then proceed with the if statement, otherwise jump out of the statement. 我猜这意味着如果car.IsSold不为null,则继续执行if语句,否则跳出该语句。 Is that right? 那正确吗? if yes, why shouldn't the programmer use 如果是,为什么程序员不应该使用

if (car.IsSold)
...

which does the exact same thing? 哪件事完全一样? I'd appreciate if someone clears this up for me. 如果有人为我解决了这个问题,我将不胜感激。

Assuming car.IsSold is nullable: 假设car.IsSold为空:

if (car.IsSold)

does not even compile since bool? bool?以来甚至不编译bool? does not implicitly cast to bool 不会隐式转换为bool


The explicit cast 显式转换

 if ((bool)car.IsSold)

will throw an exception if car.IsSold is null 如果car.IsSoldnull则将引发异常


Using the null-coalescing operator 使用空合并运算符

if (car.IsSold ?? false)

would work in this case, among other solutions. 除其他解决方案外,在这种情况下将可行。

which does the exact same thing? 哪件事完全一样?

No it doesn't. 不,不是。 Because a bool? 因为bool? (or Nullable<bool> ) and a bool are not the exact same thing. (或Nullable<bool> )和bool不是完全相同的东西。

An if condition must resolve to a bool . if条件必须解决为bool But a bool? 但是bool? might resolve to null at runtime. 可能在运行时解析为null So the compiler won't allow that. 因此,编译器将不允许这样做。 You have to provide logic in the condition which will still return a bool in the event that the value in question is null . 您必须提供逻辑条件,如果有问题的值为null ,该条件仍然会返回bool值。 Probably the simplest way to do that is the null-coalescing operator and a default literal. 可能最简单的方法是null运算符和默认文字。

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

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