在執行成員存取 (Nothing) 或索引 (?.?()) 作業之前,先測試左側作數的值,如果左側作數評估為 Nothing,則傳Nothing回 。 請注意,在通常傳回實值型別的運算式中,Null 條件運算子會傳 Nullable<T>回 。
這些運算符可協助您撰寫較少的程式代碼來處理 Null 檢查,特別是當遞減至數據結構時。 例如:
' Nothing if customers is Nothing
Dim length As Integer? = customers?.Length
' Nothing if customers is Nothing
Dim first As Customer = customers?(0)
' Nothing if customers, the first customer, or Orders is Nothing
Dim count As Integer? = customers?(0)?.Orders?.Count()
為了比較,這些表達式中第一個沒有 null 條件運算子的替代程式代碼為:
Dim length As Integer?
If customers IsNot Nothing Then
length = customers.Length
Else
length = Nothing
End If
有時候,您必須根據該物件上布爾成員的值,對可能為 Null 的對象採取動作(如下列範例中的 Boolean 屬性 IsAllowedFreeShipping ):
Dim customer = FindCustomerByID(123) 'customer will be Nothing if not found.
If customer IsNot Nothing AndAlso customer.IsAllowedFreeShipping Then
ApplyFreeShippingToOrders(customer)
End If
您可以縮短程式代碼,並避免使用 null 條件運算符手動檢查 Null,如下所示:
Dim customer = FindCustomerByID(123) 'customer will be Nothing if not found.
If customer?.IsAllowedFreeShipping Then ApplyFreeShippingToOrders(customer)
空值條件運算子是短路運算子。 如果條件式成員存取和索引作業鏈結中的一個作業傳 Nothing回 ,則鏈結的其餘執行會停止。 在下列範例中, C(E) 如果 A、 B或 C 評估為 ,則不會評估為 Nothing。
A?.B?.C?(E)
請注意,如果 Not someStr?.Contains("some string") 或 評估為 Boolean? 的任何其他值具有 或nothing的值HasValue=false,則會else執行 區塊。 評估會遵循 SQL 評估,其中 null/nothing 不等於任何專案,甚至不等於另一個 Null/nothing。
Null 條件式成員存取的另一個用途是以安全線程的方式叫用委派,而程式代碼要少得多。 下列範例會定義兩種型別: NewsBroadcaster 和 。NewsReceiver 新聞專案會由 NewsBroadcaster.SendNews 委派傳送給接收者。
Public Module NewsBroadcaster
Dim SendNews As Action(Of String)
Public Sub Main()
Dim rec As New NewsReceiver()
Dim rec2 As New NewsReceiver()
SendNews?.Invoke("Just in: A newsworthy item...")
End Sub
Public Sub Register(client As Action(Of String))
SendNews = SendNews.Combine({SendNews, client})
End Sub
End Module
Public Class NewsReceiver
Public Sub New()
NewsBroadcaster.Register(AddressOf Me.DisplayNews)
End Sub
Public Sub DisplayNews(newsItem As String)
Console.WriteLine(newsItem)
End Sub
End Class
如果調用清單中沒有專案 SendNews ,委派 SendNews 會 NullReferenceException擲回 。 在 Null 條件運算子之前,類似下列的程式代碼可確保委派調用清單不是 Nothing:
SendNews = SendNews.Combine({SendNews, client})
If SendNews IsNot Nothing Then
SendNews("Just in...")
End If
新方式更簡單:
SendNews = SendNews.Combine({SendNews, client})
SendNews?.Invoke("Just in...")
新的方式是安全線程,因為編譯程式會產生程序代碼,只評估 SendNews 一次,將結果保留在暫存變數中。 您必須明確呼叫 方法, Invoke 因為沒有 Null 條件式委派調用語法 SendNews?(String)。
另請參閱
- 運算子 (Visual Basic)
- Visual Basic 程式設計指南
- Visual Basic 語言參考