小编Ste*_*ael的帖子

否定null条件运算符会返回意外结果

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

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

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

Not l?.Any()如果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 …
Run Code Online (Sandbox Code Playgroud)

vb.net null-conditional-operator

4
推荐指数
1
解决办法
110
查看次数

标签 统计

null-conditional-operator ×1

vb.net ×1