将数学运算符分配给没有IF的变量 - System.MissingMemberException

时间:2016-02-06 11:19:00

标签: vb.net

我正在尝试通过字符串变量(cal_Operation)发送操作符号,但是我收到错误。

注意:

  • label1将保留结果
  • text1持有将对其进行计算的两个数字之一
  • text2保存将要生成的两个数字的第二个数字 对它们的计算
  • cal_Operation字符串保存操作符号( - 或+或/或 - )

代码是:

Dim cal_Operation As String
Public newops = 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}

我有单选按钮将操作分配给字符串变量
在按钮中,我插入此代码

RadioButton1_CheckedChanged(sender As Object, e As EventArgs) Handles RadioButton1.CheckedChanged
   cal_Operation = "+" 
   Dim op1 = newops(cal_Operation)
   Label1.Text = CStr(op1(CDbl(TextBox1.Text), CDbl(TextBox2.Text)))
End Sub

但我收到此错误

  

“System.MissingMemberException”类型的未处理异常   发生在Microsoft.VisualBasic.dll附加信息:否   找到类型'Func(Of Double,Double,Double)'的默认成员。

原因和解决方案是什么?

1 个答案:

答案 0 :(得分:0)

您需要更改newops字典的声明并明确其类型

Public newops as Dictionary(Of String, Func(Of Double, Double, Double)) = 
       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}}