如果变量值为Nothing,我们会遇到null条件运算符的意外行为. 以下代码的行为让我们有点困惑 Dim l As List(Of Object) = MethodThatReturnsNothingInSomeCases() If Not l?.Any() Then 'do something End If 如果l没有条
以下代码的行为让我们有点困惑
Dim l As List(Of Object) = MethodThatReturnsNothingInSomeCases()
If Not l?.Any() Then
'do something
End If
如果l没有条目或者l是Nothing,那么预期的行为是Not l?.Any()是真的.但如果我没什么,那么结果就是假的.
这是我们用来查看实际行为的测试代码.
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
结果:
>没有什么是假的
>没有什么是真的
>没什么?.Any()是假的
>什么都没有?.Any()是假的
如果评估为真,为什么不是最后一个?
C#阻止我完全写这种检查……
在VB.NET中,与C#相反,Nothing不等于或等于其他任何东西(类似于SQL).那么如果将布尔值与布尔值进行比较?没有价值的结果既不是真也不是假,相反,比较也将返回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#?
