2017-10-17 126 views
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#阻止我寫這種支票共有的...

回答

5

在VB.NET Nothing不等於或不等於別的(類似於SQL),而不是C#。因此,如果將BooleanBoolean?進行比較,結果將不是True也不是False,而是比較也會返回Nothing

在VB.NET無空值意味着一個未知值,所以如果你比較一個已知值和未知值,結果也是未知的,不是真或假。

你可以做的是使用Nullable.HasValue

Dim result as Boolean? = l?.Any() 
If Not result.HasValue Then 
    'do something 
End If 

相關:Why is there a difference in checking null against a value in VB.NET and C#?