Visual Basic Or, OrElse 仍然返回 false

Visual Basic Or, OrElse still returning false

我是 VB.net 的新手,我对此声明没有什么问题,我想在 txtBox 中抛出 msgBox txtTitul 不是 "Bc." 或 "" 或 "Ing." 。 .. 这每次都会抛出 msgBox

If Not txtTitul.Text.Equals("Bc.") _
    OrElse Not txtTitul.Text.Equals("") _
    OrElse Not txtTitul.Text.Equals("Bc.") _
    OrElse Not txtTitul.Text.Equals("Mgr.") _
    OrElse Not txtTitul.Text.Equals("Ing.") _
    OrElse Not txtTitul.Text.Equals("Mgr. art.") _
    OrElse Not txtTitul.Text.Equals("Ing. arch.") _
    OrElse Not txtTitul.Text.Equals("MUDr.") _
    OrElse Not txtTitul.Text.Equals("MVDr.") _
    OrElse Not txtTitul.Text.Equals("RNDr.") _
    OrElse Not txtTitul.Text.Equals("PharmDr.") _
    OrElse Not txtTitul.Text.Equals("PhDr.") _
    OrElse Not txtTitul.Text.Equals("JUDr.") _
    OrElse Not txtTitul.Text.Equals("PaedDr.") _
    OrElse Not txtTitul.Text.Equals("ThDr.") Then
    MsgBox("Neplatny titul!")
    Exit Sub
End If

您不想使用 OrElse,而是 AndAlso,因为只有当它不是其中之一时,它才是无效的标题(所以不是第一个 不是第二个 and 不是第三个 and 等等....).

但是我可以向您展示一种更简单且更易于维护的方法吗?

Dim allowedTitles = {"Bc.","Ing.","Ing. arch.","MUDr.","MVDr.","RNDr.","PhDr.","PaedDr.","ThDr."}
If Not allowedTitles.Contains(txtTitul.Text) Then 
    MsgBox("Invalid title!")
End If

如果你也想接受lower-case,那么忽略大小写,你可以使用:

If Not allowedTitles.Contains(txtTitul.Text, StringComparer.InvariantCultureIgnoreCase) Then 
    MsgBox("Invalid title!")
End If

考虑到您的输入是 "Bc."

Not txtTitul.Text.Equals("Bc.")  <- false
Not txtTitul.Text.Equals("")     <- true
false OrElse true = true

考虑您的输入是 "abc"

Not txtTitul.Text.Equals("Bc.")  <- true
Not txtTitul.Text.Equals("")     <- true
true OrElse true = true

解决方法可以参考Tim的回答