簡體   English   中英

如何使用 null 條件運算符安全而簡單地檢查可為 null 的引用類型的屬性

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

給出的代碼如下:

Thing? maybeAThing = GetThing();

我想編寫邏輯來安全地檢查 object 是否不是 null 並具有特定屬性:

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

但是這個語法看起來有點亂。 我認為 null 條件運算符應該讓我這樣做,因為一旦遇到 null,任何測試都會失敗:

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

但這會導致編譯器錯誤:

CS0266 不能隱式轉換bool? 布爾

似乎“可空性”正在擴展到返回值( bool? ),而不是一旦maybeAThing被確定為null ,測試就會失敗。

這是特定於 NRT 而不是可為空的值類型嗎? 有沒有辦法做到這一點而不必編寫額外的條款,如果沒有,那么我對語言工作方式的誤解是什么?

你可以寫一些變體:

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

您還可以使用屬性模式:

maybeAThing is { IsAGoodThing: true }

你可以寫:

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


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

您可以使用

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

這會將Nullable<bool>轉換為bool

解除運營商

對於等於運算符==,如果兩個操作數都是null,則結果為真,如果只有一個操作數是null,則結果為假; 否則,比較操作數包含的值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM