【问题标题】:VB.NET - How to use array literal in a condition?VB.NET - 如何在条件中使用数组文字?
【发布时间】:2011-10-17 22:21:58
【问题描述】:

我刚刚学习了如何在 VB.NET 中创建一个数组字面量。

Dim MyArray = New Integer() { 1, 2, 3 }
' Or
Dim MyArray() As Integer = { 1, 2, 3 }
' Or
Dim MyArray() = { 1, 2, 3 }
' Or
Dim MyArray() = { 1, 2, "A", "B" }

现在,我想在条件中使用 A LITERAL ARRAY(请参阅伪代码)

If 1 exists in {1,2,3,4} Then
    MsgBox "Exists!"
End If

但我不知道如何,似乎您必须先将其分配给变量,然后才能在条件中使用它。

    Dim MyArray() As Integer = {3, 2, 3}
    If (MyArray.Contains(1)) Then
        MsgBox("exists!")
    Else
        MsgBox("does not exist!")
    End If

上面的代码有效,但我只是想知道有没有办法在不先将数组文字分配给变量的情况下做到这一点?

提前致谢!

【问题讨论】:

    标签: vb.net arrays conditional-statements literals


    【解决方案1】:

    为此使用{1,2,3,4}.Contains(1)

    【讨论】:

    • 我不知道它会起作用! :) 也许代码看起来很不常见,所以我没有尝试过。我也试过这个(New Integer() {3, 1, 3}).Contains(1) 它更优雅。谢谢!
    • 如果答案是蛇,我可能会被它杀死,它已经在我面前了!
    猜你喜欢
    • 1970-01-01
    • 2014-01-10
    • 1970-01-01
    • 2013-08-04
    • 2019-05-09
    • 1970-01-01
    • 2016-07-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多