仅在case语句中使用枚举的情况1(Visual Basic)

时间:2013-10-15 01:48:23

标签: vb.net enumeration select-case

程序应该使用Select Case语句中开头声明的枚举类型。当我运行程序时,无论我选择哪个运算符,它只使用第一个case语句(用于添加)。我尝试在case语句中重新排列它们以查看它是否只使用了第一个,但它仍然只是选择了add。我做错了什么?

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 

1 个答案:

答案 0 :(得分:1)

您永远不会分配CalcOperator,因此它始终是整数的默认值,0 - add中的enum

您可以在ComboBox更改时添加事件以进行更改,也可以在btnCalculate_Click上执行此操作。如果您在其他地方不需要它,您可以在Click事件中执行此操作:

CalcOperator = CType(cboOperator.SelectedItem, OperatorEnum)