VB.NET 用变量评估字符串
VB.NET Evaluate a string with variables
我喜欢用不同的公式填充我的数据库。
当我在数据库中有一个像 "(2+4)*5"
这样的公式时,我得到的结果是 40
:
update DB.dbo.INFOGROUP SET formula = '(2+4)*5' where INFOGROUP = 'S42'
当我在数据库中有一个像 "(x+4)*5"
这样的公式时,我得到了结果 20
。即使我将 x
的值设置为 10
:
,x
值也会被忽略
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)
.
这样的函数
脚本引擎不知道您的方法中的变量。
如果要计算包含变量的公式,则需要告诉它该变量具有什么值:
SC.Language = "VBSCRIPT"
sc.AddCode "Private Const x = 10"
Dim Result As Double = Convert.ToDouble(SC.Eval(Formula))
我喜欢用不同的公式填充我的数据库。
当我在数据库中有一个像 "(2+4)*5"
这样的公式时,我得到的结果是 40
:
update DB.dbo.INFOGROUP SET formula = '(2+4)*5' where INFOGROUP = 'S42'
当我在数据库中有一个像 "(x+4)*5"
这样的公式时,我得到了结果 20
。即使我将 x
的值设置为 10
:
x
值也会被忽略
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)
.
脚本引擎不知道您的方法中的变量。 如果要计算包含变量的公式,则需要告诉它该变量具有什么值:
SC.Language = "VBSCRIPT"
sc.AddCode "Private Const x = 10"
Dim Result As Double = Convert.ToDouble(SC.Eval(Formula))