2017-10-17 127 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#?