VB.NET中,不使用null条件运算符可能导致哪些意外的返回结果?
- 内容介绍
- 文章标签
- 相关推荐
本文共计520个文字,预计阅读时间需要3分钟。
如果变量值为Nothing,将遇到null运算符的特殊行为。以下代码的行为可能让人困惑:
vbaDim l As List(Of Object)=MethodThatReturnsNothingInSomeCases()If Not l.Any() Then 'do somethingEnd If
如果l没有元素,`l.Any()`将返回False,因此上面的代码块中的`'do something`部分将不会执行。
如果变量值为Nothing,我们会遇到null条件运算符的意外行为.以下代码的行为让我们有点困惑
Dim l As List(Of Object) = MethodThatReturnsNothingInSomeCases() If Not l?.Any() Then 'do something End If
如果l没有条目或者l是Nothing,那么预期的行为是Not l?.Any()是真的.但如果我没什么,那么结果就是假的.
这是我们用来查看实际行为的测试代码.
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()是假的
>什么都没有?.Any()是假的
如果评估为真,为什么不是最后一个?
C#阻止我完全写这种检查……
在VB.NET中,没有值的可空值意味着未知值,因此如果将已知值与未知值进行比较,结果也是未知的,不是真或假.
你可以做的是使用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#?
本文共计520个文字,预计阅读时间需要3分钟。
如果变量值为Nothing,将遇到null运算符的特殊行为。以下代码的行为可能让人困惑:
vbaDim l As List(Of Object)=MethodThatReturnsNothingInSomeCases()If Not l.Any() Then 'do somethingEnd If
如果l没有元素,`l.Any()`将返回False,因此上面的代码块中的`'do something`部分将不会执行。
如果变量值为Nothing,我们会遇到null条件运算符的意外行为.以下代码的行为让我们有点困惑
Dim l As List(Of Object) = MethodThatReturnsNothingInSomeCases() If Not l?.Any() Then 'do something End If
如果l没有条目或者l是Nothing,那么预期的行为是Not l?.Any()是真的.但如果我没什么,那么结果就是假的.
这是我们用来查看实际行为的测试代码.
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()是假的
>什么都没有?.Any()是假的
如果评估为真,为什么不是最后一个?
C#阻止我完全写这种检查……
在VB.NET中,没有值的可空值意味着未知值,因此如果将已知值与未知值进行比较,结果也是未知的,不是真或假.
你可以做的是使用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#?

