简体   繁体   English

如何使用 null 条件运算符安全而简单地检查可为 null 的引用类型的属性

[英]How can I use the null-conditional operator to safely and briefly check a nullable reference type's property

Given code like:给出的代码如下:

Thing? maybeAThing = GetThing();

I want to write logic that safely checks if the object is not null and has a certain property:我想编写逻辑来安全地检查 object 是否不是 null 并具有特定属性:

if(maybeAThing is not null && maybeAThing.IsAGoodThing){... }

But this syntax seems a bit messy.但是这个语法看起来有点乱。 I thought the null-conditional operators were supposed to let me do this as any test will fail as soon as null is encountered:我认为 null 条件运算符应该让我这样做,因为一旦遇到 null,任何测试都会失败:

if(maybeAThing?.IsAGoodThing){...}

But this gives compiler error:但这会导致编译器错误:

CS0266 cannot implicitly convert bool? CS0266 不能隐式转换bool? to bool布尔

It seems the 'nullableness' is extending to the return value ( bool? ) instead of the test failing as soon as maybeAThing is determined to be null .似乎“可空性”正在扩展到返回值( bool? ),而不是一旦maybeAThing被确定为null ,测试就会失败。

Is this specific to NRTs rather than nullable value types?这是特定于 NRT 而不是可为空的值类型吗? Is there a way to do this without having to write additional clauses, and if not then what is my misunderstanding in the way the language works?有没有办法做到这一点而不必编写额外的条款,如果没有,那么我对语言工作方式的误解是什么?

You can write some variant of:你可以写一些变体:

maybeAThing?.IsAGoodThing == true
maybeAThing?.IsAGoodThing ?? false
(maybeAThing?.IsAGoodThing).GetValueOfDefault(false)

You can also use a property pattern:您还可以使用属性模式:

maybeAThing is { IsAGoodThing: true }

You can just write:你可以写:

if(maybeAThing?.IsAGoodThing == true){...}


null == true  //Nope
false == true //Nope
true == true  //Yes

You can use您可以使用

if(maybeAThing?.IsAGoodThing == true){...}

This converts the Nullable<bool> to a bool .这会将Nullable<bool>转换为bool

Lifted Operators 解除运营商

For the equality operator ==, if both operands are null, the result is true, if only one of the operands is null, the result is false;对于等于运算符==,如果两个操作数都是null,则结果为真,如果只有一个操作数是null,则结果为假; otherwise, the contained values of operands are compared.否则,比较操作数包含的值。

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

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