在 case 语句中使用枚举仅使用 Case 1 (Visual Basic)
Posted
技术标签:
【中文标题】在 case 语句中使用枚举仅使用 Case 1 (Visual Basic)【英文标题】:Only uses Case 1 using enumeration in case statement (Visual Basic) 【发布时间】:2013-10-15 01:48:22 【问题描述】:该程序应该使用在 Select Case 语句中开头声明的枚举类型。当我运行程序时,无论我选择哪个运算符,它都只使用第一个 case 语句(用于添加)。我尝试在 case 语句中重新排列它们以查看它是否只使用了第一个,但它仍然只是选择了添加。我做错了什么?
Public Class Assignment2Calculator
Dim Operand1 As Decimal
Dim Operand2 As Decimal
Dim CalcOperator As Integer
Enum OperatorEnum
add
divide
multiply
subtract
End Enum
Private Sub Assignment2Calculator_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
cboOperator.DataSource = [Enum].GetValues(GetType(OperatorEnum))
AcceptButton = btnCalculate
End Sub
Private Sub IsValidData(ByVal txtOperand1 As Object, ByVal txtOperand2 As Object)
Operand1 = Convert.ToDecimal(txtOperand1.Text)
Operand2 = Convert.ToDecimal(txtOperand2.Text)
If (Operand1 > 0 Or Operand1 < 1000000) And (Operand2 > 0 Or Operand2 < 1000000) Then
If IsNumeric(Operand1) And IsNumeric(Operand2) Then
End If
Else
MessageBox.Show("Operand 1 or 2 is not valid")
End If
End Sub
Private Sub btnCalculate_Click(sender As System.Object, e As System.EventArgs) Handles btnCalculate.Click
IsValidData(txtOperand1, txtOperand2)
Calculate(Operand1, Operand2, CalcOperator)
End Sub
Private Sub Calculate(ByVal Operand1 As Decimal, ByVal Operand2 As Decimal, _
ByVal CalcOperator As Integer)
'Performs requested operation using select case and enumeration
Dim answer As Decimal
Dim CalcOperatorCase As OperatorEnum
Select Case CalcOperatorCase
Case Is = OperatorEnum.add
answer = Operand1 + Operand2
txtResult.Text = FormatNumber(answer, 3)
Case Is = OperatorEnum.divide
answer = Operand1 - Operand2
txtResult.Text = FormatNumber(answer, 3)
Case Is = OperatorEnum.multiply
answer = Operand1 * Operand2
txtResult.Text = FormatNumber(answer, 3)
Case Is = OperatorEnum.subtract
answer = Operand1 / Operand2
txtResult.Text = FormatNumber(answer, 3)
Case Else
MessageBox.Show("Please select an operator")
End Select
End Sub
End Class
【问题讨论】:
您对无效操作数的测试似乎是错误的。如果 Operand1 是 -1,它仍然会通过 If 测试。您应该将 Or 更改为 AndAlso。 【参考方案1】:您从不分配CalcOperator
,因此它始终是整数的默认值,即0
- 在您的enum
中为add
。
您可以添加一个事件以在您的ComboBox
更改时更改它,或者您可以在btnCalculate_Click
上进行更改。如果您在其他任何地方都不需要它,不妨在Click
事件中进行:
CalcOperator = CType(cboOperator.SelectedItem, OperatorEnum)
【讨论】:
非常感谢!我非常感谢您的帮助以上是关于在 case 语句中使用枚举仅使用 Case 1 (Visual Basic)的主要内容,如果未能解决你的问题,请参考以下文章