在If语句中使用Or

And*_*ics 1 .net vb.net validation if-statement

我对vb.net编码很新.我搜查了一下,但没有找到能解决问题的东西.

If Number.Text = "974.823" Or Number.Text = "231.65" Or Number.text = "567.32" Or Number.text = "476.45" Or Number.text = "149.39" Or Number.text = "675.19" Then
    win.text = "Success"
Else
    Stop
End If
Run Code Online (Sandbox Code Playgroud)

我试过了OrElse,但它也没用.

If Number.Text = "974.823" OrElse Number.Text = "231.65" OrElse Number.text = "567.32" OrElse Number.text = "476.45" OrElse Number.text = "149.39" OrElse Number.text = "675.19" Then 
    win.text = "Success" 
Else 
    Stop 
End If
Run Code Online (Sandbox Code Playgroud)

Mat*_*lko 5

首先,您发布的代码应该有效.它不起作用的唯一原因是它不Number.Text等于你的条件中的一个值(它是否有空格或其他一些字符?)

其次,如果您使用这样的数值,您应该比较数字数据类型而不是字符串.您可以使用TryParse以确保值的类型正确.

第三Case,如果你有多个Or语句,那么使用语句可以提高可读性.

所以我会建议这样的事情:

    Dim d As Decimal

    'See if the value can be parsed into the appropriate numeric type. 
    'If not show an error
    If Not Decimal.TryParse(Number.Text, d) Then
        MsgBox("The value entered in invalid")
        Return
    End If

    'Use a Select Case statement comparing the Decimal with other values
    'The D after the number tells the compiler that this is a decimal value
    Select Case d
        Case 974.823D, 231.65D, 567.32D, 476.45D, 149.39D, 675.19D
            win.text = "Success"
        Case Else
            Stop
    End Select
Run Code Online (Sandbox Code Playgroud)