Assign a math operator to a variable - VB

[亡魂溺海] 提交于 2019-12-24 01:54:16

问题


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?


回答1:


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))



回答2:


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();


来源:https://stackoverflow.com/questions/22236677/assign-a-math-operator-to-a-variable-vb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!