2015-12-07 32 views
1

我有计划,需要这样的用户输入:“附加信息:从字符串”yes“转换为键入”Boolean“无效。”

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 

这给出了错误:在修复这怎么

An unhandled exception of type 'System.InvalidCastException' occurred in Microsoft.VisualBasic.dll

Additional information: Conversion from string "yes" to type 'Boolean' is not valid.

理念,使“是”或“是”不会导致无效的错误异常?

回答

1

表达式(yesorno =“是”或“yes”)计算结果为(布尔或字符串)这会导致异常。因为布尔值正在与一个字符串进行比较。

试试这个代码: -

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 
2

是:

If yesorno = "Yes" Or yesorno = "yes" Then 

但最好使用权StringComparisonString.Equals

If String.Equals(yesorno, "YES", StringComparison.CurrentCultureIgnoreCase) Then 

,你也应该使用OrElse,而不是这是一个短路操作:

If yesorno = "Yes" OrElse yesorno = "yes" Then 

否则双方总是评估,e如果第一个已经是True。它可以是与类似的问题:

If yesorno Is Nothing Or yesorno.Length = 0 Then 

此抛出即使第一个表达式已经评价true异常。

相关问题