Вопрос

I'm doing a pretty simple project for a class and just wondering if I'm going about it in the right way. We are making a clone of the Windows calculator.

For each of the math operators my code is as follows:

Private Sub btnPlus_Click(sender As Object, e As EventArgs) Handles btnPlus.Click
    If opPressed = True Then
        Select Case (opType)
            Case "+"
                txtField.Text = CStr(CDbl(opStore) + CDbl(txtField.Text))
            Case "-"
                txtField.Text = CStr(CDbl(opStore) - CDbl(txtField.Text))
            Case "*"
                txtField.Text = CStr(CDbl(opStore) * CDbl(txtField.Text))
            Case "/"
                txtField.Text = CStr(CDbl(opStore) / CDbl(txtField.Text))
        End Select
        opPressed = True
        opType = "+"
    Else
        opStore = txtField.Text
        txtField.Clear()
        opPressed = True
        opType = "+"
    End If
End Sub

Is there a way I could simply store an operator in a variable, and then have a line: txtField.Text = CStr(CDbl(opStore) variableHere CDbl(txtField.Text))? I am already storing what operator is used, so is there any easy way to convert that out of a string, and use it as an operator?

Это было полезно?

Решение

If you want something different, you could have a member variable of type Dictionary(Of String, Func(Of Double, Double, Double)) to associate a string operator with the actual logic for the operator:

Private _ops = New Dictionary(Of String, Func(Of Double, Double, Double))() From {
    {"+", Function(x, y) x + y},
    {"-", Function(x, y) x - y},
    {"*", Function(x, y) x * y},
    {"/", Function(x, y) x / y}
}

And then use that in your button click handler:

Dim op = _ops(opType)
txtField.Text = CStr(op(CDbl(opStore), CDbl(txtField.Text))

Другие советы

You could use NCalc for this - http://ncalc.codeplex.com/

string fullExpression;
string opType = "+";

fullExpression = opStore + opType + txtField.Text;
Expression e = new Expression(fullExpression);

txtField.Text = e.Evaluate().ToString();
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top