否定空条件运算符对于空值的返回结果出乎意料。

5

如果变量值为Nothing,则使用null条件运算符会出现意外行为。

以下代码的行为让我们有些困惑。

  Dim l As List(Of Object) = MethodThatReturnsNothingInSomeCases()
  If Not l?.Any() Then
    'do something
  End If 

期望的行为是,当列表l没有任何元素或l为Nothing时,Not l?.Any()应为真值。但如果l为Nothing,则结果为假值。

这是我们用来查看实际行为的测试代码。

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

结果:

  • 没有假值
  • 不是没有,那就是真值
  • Nothing?.Any() 是假值
  • Not Nothing?.Any() 也是假值

为什么最后一个 if 语句没有返回 true?

C#禁止这种检查写法…

1个回答

7
在 VB.NET 中,与 SQL 相似,Nothing 不等于或不等于其他任何东西,而 C# 则不同。因此,如果您将一个没有值的 Boolean? 与一个 Boolean 进行比较,结果既不是 True 也不是 False,相反,比较结果也将返回 Nothing
在 VB.NET 中,没有值的可空类型表示一个未知的值,因此,如果您将已知值与未知值进行比较,则结果也是未知的,而不是 true 或 false。
您可以使用Nullable.HasValue 来解决这个问题:
Dim result as Boolean? = l?.Any()
If Not result.HasValue Then
    'do something
End If 

相关: 为什么在 VB.NET 和 C# 中检查 null 和值之间会存在差异?


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接