我的程序需要用户输入,如下所示:
Dim yesorno = InputBox("Do you have more credit cards?", "Thomas Shera")
If yesorno = "Yes" Or "yes" Then
Name = InputBox("You are a rich person, enjoy infinite credit card bill.")
Else
MsgBox("You poor person, you have only " & dcreditcards & " credit cards.")
End If
违规第二行具体:
If yesorno = "Yes" Or "yes" Then
这给出了错误:
Microsoft.VisualBasic.dll中出现未处理的“System.InvalidCastException”类型异常
附加信息:从字符串“yes”到“Boolean”类型的转换无效。
想法修复这个如何,使“是”或“是”不会导致无效的错误异常?
答案 0 :(得分:2)
是:
If yesorno = "Yes" Or yesorno = "yes" Then
但最好在StringComparison
中使用正确的String.Equals
:
If String.Equals(yesorno, "YES", StringComparison.CurrentCultureIgnoreCase) Then
您还应该使用OrElse
而不是短路运营商:
If yesorno = "Yes" OrElse yesorno = "yes" Then
否则,即使第一个已经True
,也会始终评估双方。这可能是一个问题,如:
If yesorno Is Nothing Or yesorno.Length = 0 Then
即使第一个表达式已经评估为true
,它也会引发异常。
答案 1 :(得分:1)
表达式(yesorno =“是”或“是”)求值为(Boolean或String)这会导致异常。正在将布尔值与字符串进行比较。
试试这段代码: -
Dim yesorno = InputBox("Do you have more credit cards?", "Thomas Shera")
If yesorno.ToUpper = "YES" Then
Name = InputBox("You are a rich person, enjoy infinite credit card bill.")
Else
MsgBox("You poor person, you have only " & dcreditcards & " credit cards.")
End If