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#阻止我写这种支票共有的...