我喜欢用不同的公式填充数据库。
当我在数据库中有一个"(2+4)*5"
之类的公式时,得到的结果40
:
update DB.dbo.INFOGROUP SET formula = '(2+4)*5' where INFOGROUP = 'S42'
当我在数据库中有一个"(x+4)*5"
之类的公式时,我得到的结果是20
。即使将x
的值设置为x
,也会忽略10
的值:
update DB.dbo.INFOGROUP SET formula = '(x+4)*5' where INFOGROUP = 'S42'
Private Sub BtnCalculate_Click(sender As Object, e As EventArgs) Handles BtnCalculate.Click
Dim SC As New MSScriptControl.ScriptControl
Dim x As Double = 10
SQL.AddParam("@infogroup", "S42")
SQL.ExecQuery($"SELECT formula FROM DB.dbo.INFOGROEP where infogroep=@infogroep")
Dim Formula As String = <string_from_db>
'SET LANGUAGE TO VBSCRIPT
SC.Language = "VBSCRIPT"
'ATTEMPT MATH
Try
Dim Result As Double = Convert.ToDouble(SC.Eval(Formula))
'SHOW THAT IT WAS VALID
MessageBox.Show("Math success, " & Formula & " equals " & Result.ToString)
Catch ex As Exception
'SHOW THAT IT WAS INVALID
MessageBox.Show("Not a valid math formula for a double.")
End Try
End Sub
这完全有可能吗?或者我需要第三方脚本吗?
顺便说一句:在Visual Foxpro中,有一个类似EVAL(db_string)
的函数。
答案 0 :(得分:2)
脚本引擎不了解方法中的变量。 如果要评估包含变量的公式,则需要告诉它该变量具有什么值:
SC.Language = "VBSCRIPT"
sc.AddCode "Private Const x = 10"
Dim Result As Double = Convert.ToDouble(SC.Eval(Formula))