我正在使用我的第一个VB.NET控制台应用程序,而且我很难用(可能)非常简单的概念.我需要将用户键入的内容与一系列字符串进行比较.
这是我到目前为止:
Console.WriteLine("Is there a 2nd IIS Server? (y/n)")
If Console.ReadLine() = "Yes" Or "yes" Or "Y" Or "y" Then
Servers.IISsvr2 = Console.ReadLine()
End If
Run Code Online (Sandbox Code Playgroud)
我知道这里的=运算符不正确,因为那是布尔值.我应该检查一系列布尔检查吗?或者有更好的方法来处理这种情况吗?
该=运营商是完全正确的; 这是你的其余Or操作系统错了!
这是人们在每种语言中犯下的一个非常常见的错误,而事实是,它只是不起作用.编程语言并不神奇.Or获取一个操作数和另一个操作数并返回布尔值或整数.它的优先级低于=.你必须每次都指定比较,否则它将永远是True.
Console.WriteLine("Is there a 2nd IIS Server? (y/n)")
Dim line As String = Console.ReadLine()
If line = "Yes" Or line = "yes" Or line = "Y" Or line = "y" Then
Servers.IISsvr2 = Console.ReadLine()
End If
Run Code Online (Sandbox Code Playgroud)
另外,用于OrElse防止不必要的比较(当操作数是布尔值时,它几乎总是你想要的):
Console.WriteLine("Is there a 2nd IIS Server? (y/n)")
Dim line As String = Console.ReadLine()
If line = "Yes" OrElse line = "yes" OrElse line = "Y" OrElse line = "y" Then
Servers.IISsvr2 = Console.ReadLine()
End If
Run Code Online (Sandbox Code Playgroud)
Select Case 在某些情况下也很有趣,但这可能不合适:
Select Case Console.ReadLine()
Case "Yes", "yes", "Y", "y"
Servers.IISsvr2 = Console.ReadLine()
End Select
Run Code Online (Sandbox Code Playgroud)
提示,有人吗?
Function BooleanPrompt(prompt As String) As Boolean
Do
Console.Write("{0} (y/n) ", prompt)
Select Case Console.ReadLine().ToLower()
Case "y", "yes"
Return True
Case "n", "no"
Return False
End Select
Loop
End Function
Run Code Online (Sandbox Code Playgroud)