【问题标题】:"Additional information: Conversion from string "yes" to type 'Boolean' is not valid."“附加信息:从字符串“yes”到类型“Boolean”的转换无效。”
【发布时间】:2015-12-07 12:55:29
【问题描述】:

我的程序需要这样的用户输入:

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”的转换无效。

关于如何解决此问题的想法,使“是”或“是”不会导致无效错误异常?

【问题讨论】:

    标签: vb.net


    【解决方案1】:

    它是:

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

    但最好在String.Equals中使用正确的StringComparison

    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,这也会引发异常。

    【讨论】:

      【解决方案2】:

      表达式 (yesorno = "Yes" Or "yes") 计算结果为 (Boolean Or 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
      

      【讨论】:

        猜你喜欢
        • 2018-06-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-07-30
        • 2015-02-09
        • 1970-01-01
        相关资源
        最近更新 更多