2017-10-17 9 views
4

変数値が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

答えて

5

は、(SQLに似ている)他の何かに等しいか等しくないではありません...完全チェックのこの種を書いてから私を防ぎます。したがって、Booleanと値が一致しないBoolean?を比較すると、結果はTrueでもFalseでもなく、代わりにNothingが返されます。

VB.NETで値なしのnullableは、の未知の値を意味するので、既知の値と未知の値を比較すると、結果も不明で、真または偽ではありません。あなたは何ができるか

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#?

関連する問題