5

如果变量值为 Nothing,我们会遇到与 null 条件运算符有关的意外行为。

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

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

Not l?.Any()如果l没有条目或什么都没有,则预期的行为是真实l的。但如果lis 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

结果:

  • 没有什么是假的
  • 不是没有什么是真实的
  • 什么都没有?.Any() 是假的
  • Not Nothing?.Any() 是假的

如果评估为真,为什么不是最后一个?

C# 完全阻止我编写这种检查......

4

1 回答 1

6

在 VB.NETNothing中不等于或不等于其他任何东西(类似于 SQL),而不是 C#。因此,如果您将 aBooleanBoolean?没有值的 a 进行比较,则结果既不是True也不是False,而是比较也会返回Nothing

在 VB.NET 中,没有值的 nullable 表示未知值,因此如果将已知值与未知值进行比较,结果也是未知的,而不是真或假。

你可以做的是使用Nullable.HasValue

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

相关:为什么根据 VB.NET 和 C# 中的值检查 null 有区别?

于 2017-10-17T10:59:58.580 回答