【问题标题】:Shortcut for vb null and Any() checksvb null 和 Any() 检查的快捷方式
【发布时间】:2021-03-03 13:26:59
【问题描述】:

如果之前问过我很抱歉......如果是这样,我没有找到它。

我正在阅读A Shortcut for c# null and Any() checks,我看到了接受的答案。我理解答案,尽管大多数人使用 x.Items?.Any() ??假的。

我的问题是:如何做到这一点是 VB.NET

我可以简单写一下吗

If x.Items?.Any() Then

或者我需要

If x.Items?.Any() = True Then

虽然 if (x.Items?.Any()) 不能在 C# 中编译,但它们都可以在 VB 中编译...但这并不总是意味着它们都是正确的 :-)

【问题讨论】:

  • 如果 Items 可以为空,那么 Any() 将返回 bool?。所以应该是=True,避免null。
  • 据我所知,这是因为 VB 自动转换 bool 而编译的?布尔值。如果这些值在运行时确实为 null,这显然会崩溃。但这会是空的吗?
  • 其实在if情况下两者都不会崩溃。因为有确切的类型比较。如果 items 为 null,则 true 或 false 都不等于 null。
  • 我什至无法在 .NET Fiddle 上进行测试:s dotnetfiddle.net/5K5GE5
  • 选择编译器 Roslyn 3.8

标签: vb.net linq


【解决方案1】:

当我在 LinqPad 上测试以下内容时:

Dim lst As List(Of Vehicle) = Nothing
If lst?.Any Then
    Console.WriteLine("True")
Else
    Console.WriteLine("False")
End If

它工作得很好,打印False,即使是Option Strict On

它也可以在 .NET 5 控制台应用程序的 Visual Studio 中工作。

Visual Basic 似乎支持在If 语句的测试中使用Boolean?

现在它似乎可以工作了on .NET Fiddle

【讨论】:

  • 您的代码将解析为False,因为? 快捷方式解析为null/Nothing,而Any() 甚至没有经过测试。如果lst 不为空而是为空(即= New List(Of Vehicle)),由于Any() 测试,它将解析为False
  • @SteveCinq 我不太确定你想说什么。这不是重点吗?无论列表是Nothing,还是列表为空,都会执行If的“else”分支。
  • 只是突出“为什么”的一面。不是批评。
【解决方案2】:

在 .NET Fiddle 上做了一些测试后,我发现两者都有效

Imports System
Imports System.Linq
            
Public Module Module1
  public Class Vehicle

  End Class

  Public Sub Main()

    Dim x as System.Collections.Generic.List(Of Vehicle)
    
    Dim y as System.Collections.Generic.List(Of Vehicle)
    y = new System.Collections.Generic.List(of Vehicle)
    
    Dim z as System.Collections.Generic.List(Of Vehicle)
    z = new System.Collections.Generic.List(of Vehicle)
    
    z.Add(new Vehicle())
        
    If (x?.Any() = True) Then
        Console.WriteLine("X YES")
    Else
        Console.WriteLine("X NO")
    End If
    
    If (x?.Any()) Then
        Console.WriteLine("X YES")
    Else
        Console.WriteLine("X NO")
    End If
    
    If (y?.Any() = True) Then
        Console.WriteLine("Y YES")
    Else
        Console.WriteLine("Y NO")
    End If
    
    If (y?.Any()) Then
        Console.WriteLine("Y YES")
    Else
        Console.WriteLine("Y NO")
    End If
    
    If (z?.Any() = True) Then
        Console.WriteLine("Z YES")
    Else
        Console.WriteLine("Z NO")
    End If
    
    If (z?.Any()) Then
        Console.WriteLine("Z YES")
    Else
        Console.WriteLine("Z NO")
    End If
End Sub
End Module

会导致

X NO
X NO
Y NO
Y NO
Z YES
Z YES

如预期的那样

【讨论】:

  • 去掉括号会怎样?
猜你喜欢
  • 2015-05-08
  • 2015-09-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多