如果重要,我使用的是Visual Studio Express 2012和Windows 7 Professional。
我有简单的VB程序抛出此异常:
Microsoft.VisualBasic.dll中出现未处理的“System.InvalidCastException”类型异常
从字符串“s”到“布尔”类型的转换无效。
这是代码中很麻烦的部分:
If stroperation = "S" Or "s" Then
我做错了什么?
整个VB程序:
Public Class MainForm
Public stroperation, strnumber1, strnumber2, strresult As String
Public decnumber1, decnumber2, decresult As Decimal
Public operation
Private Sub calculateButton_Click(sender As Object, e As EventArgs) Handles calculateButton.Click
operation = operationTextBox.Text
stroperation = CStr(operation)
strnumber1 = number1TextBox.Text
decnumber1 = CDec(strnumber1)
strnumber2 = number2TextBox.Text
decnumber2 = CDec(strnumber2)
If stroperation = "S" Or "s" Then
decresult = decnumber1 - decnumber2
resultLabel.Text = "Difference: " & strresult
ElseIf stroperation = "A" Or "a" Then
decresult = decnumber1 + decnumber2
resultLabel.Text = "Sum: " & strresult
Else
MsgBox("Enter A, a, S, or S.")
End If
End Sub
End Class
答案 0 :(得分:3)
您需要将其更改为If stroperation = "S" Or stroperation = "s" Then
或者更好的是,你可以这样做:
If stroperation.Equals("S", StringComparison.CurrentCultureIgnoreCase) Then