4
如果變量值爲Nothing,我們遇到了空條件運算符的意外行爲。否定空條件運算符返回意外結果爲空
下面的代碼的行爲讓我們有點糊塗
Dim l As List(Of Object) = MethodThatReturnsNothingInSomeCases()
If Not l?.Any() Then
'do something
End If
預期的行爲是Not l?.Any()
是truthy如果l
沒有進入或者l
什麼都不是。但如果l
是沒有結果是虛假的。
這是我們用來查看實際行爲的測試代碼。
Imports System
Imports System.Collections.Generic
Imports System.Linq
Public Module Module1
Public Sub Main()
If Nothing Then
Console.WriteLine("Nothing is truthy")
ELSE
Console.WriteLine("Nothing is falsy")
End If
If Not Nothing Then
Console.WriteLine("Not Nothing is truthy")
ELSE
Console.WriteLine("Not Nothing is falsy")
End If
Dim l As List(Of Object)
If l?.Any() Then
Console.WriteLine("Nothing?.Any() is truthy")
ELSE
Console.WriteLine("Nothing?.Any() is falsy")
End If
If Not l?.Any() Then
Console.WriteLine("Not Nothing?.Any() is truthy")
ELSE
Console.WriteLine("Not Nothing?.Any() is falsy")
End If
End Sub
End Module
結果:??
- 沒有什麼falsy
- 沒有什麼是truthy
- 沒有。任何()是falsy
- 沒有什麼。任何()是falsy
爲什麼不是最後如果評估爲真?
C#阻止我寫這種支票共有的...