変数値がNothingの場合、NULL条件付き演算子で予期しない動作が発生しました。次のコードの振る舞いが私たちを保つnull条件付き演算子を否定すると、予期しない結果が返されます。
はビットが予想される動作はl
はエントリがない場合Not l?.Any()
がtruthyであるということですかl
場合は何もありません
Dim l As List(Of Object) = MethodThatReturnsNothingInSomeCases()
If Not l?.Any() Then
'do something
End If
を混同しました。しかし、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
結果:??
- 何も何も
- 何も.ANY( truthyありません
- falsyではありません)ではない何も.ANY(
- falsyです)falsy です
評価が真であるのはなぜ最後のものではないのですか?
のC#は、C#とは対照的に、VB.NET Nothing
で