将数学运算符分配给变量

将数学运算符分配给变量

本文介绍了将数学运算符分配给变量-VB的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为一个班级做一个非常简单的项目,只是想知道我是否正在以正确的方式进行工作.我们正在克隆Windows计算器.

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

有没有一种方法可以简单地将运算符存储在变量中,然后有一行:txtField.Text = CStr(CDbl(opStore) variableHere CDbl(txtField.Text))?我已经存储了使用的运算符,那么是否有任何简单的方法可以将其转换为字符串并将其用作运算符?

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?

推荐答案

如果您想要不同的东西,则可以使用类型为Dictionary(Of String, Func(Of Double, Double, Double))的成员变量将字符串运算符与该运算符的实际逻辑相关联:

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

这篇关于将数学运算符分配给变量-VB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-10 23:26