【问题标题】:Compact many ORs into one If Statement将多个 OR 压缩为一个 If 语句
【发布时间】:2021-03-01 02:35:44
【问题描述】:

我想在一个 IF 语句中使用多个 OR 语句,但显然它最终是这样的:

If x = this or x = that or x = these or x = those Then

有没有办法把它压缩成一个更小的语句? 例如

If x = {this, that, those, these}

【问题讨论】:

标签: vb.net


【解决方案1】:

您可以使用Contains 来确定列表是否包含您的值。假设整数

Dim vals As New List(Of Integer)(New Integer() {this, that, those})

If vals.Contains(x) Then
   ' do something
End If

【讨论】:

  • 事实上,你可能会做If {this, that, those}.Contains(x) Then '...
【解决方案2】:

可以使用Select Case。作为一个例子,只是一些代码

Dim x As String
x = "this"
Select Case x
    Case "this", "that", "these","those"
        ' Do this that 
    Case "other this", "other that"
        ' do other this that 
    Case Else
End Select

或者您使用建议的列表here

【讨论】:

    猜你喜欢
    • 2016-04-26
    • 1970-01-01
    • 1970-01-01
    • 2017-05-06
    • 1970-01-01
    • 1970-01-01
    • 2016-03-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多