空條件運算子
為了避免冗長的空檢查,已經在語言中引入了 ?.
運算子。
舊的詳細語法:
placeholderCopyIf myObject IsNot Nothing AndAlso myObject.Value >= 10 Then
現在可以簡潔地取代:
placeholderCopyIf myObject?.Value >= 10 Then
當你擁有一系列屬性時,?
運算子特別強大。考慮以下:
placeholderCopyDim fooInstance As Foo = Nothing
Dim s As String
通常你必須寫這樣的東西:
placeholderCopyIf fooInstance IsNot Nothing AndAlso fooInstance.BarInstance IsNot Nothing Then
s = fooInstance.BarInstance.Baz
Else
s = Nothing
End If
但是使用 ?
運算子,可以用以下程式碼替換:
placeholderCopys = fooInstance?.BarInstance?.Baz