在 vb.net 中进行数学计算,就像在 javascript 中进行 Eval 一样

发布于 2024-08-05 18:17:30 字数 240 浏览 2 评论 0原文

有没有什么方法可以解析 vb.net 中的字符串(例如内置方法),可以像 Eval 一样进行数学运算?例如,3+(7/3.5) 作为字符串将返回 2。

我并不是要求您为我编写此代码,我只是想知道是否有内置方法可以做到这个,如果没有我会自己编码。

我可以打赌它无法自行解析像 Sin(90) 这样的东西,而且我知道它需要被 Math.Sin(90) 替换。

如果有内置方法,如何使用它?

Is there any way to parse a string in vb.net (like, built in methods), that can do math like Eval can? For example, 3+(7/3.5) as a string would return 2.

I am not asking for you to code this for me, I just want to know if there is a built in way to do this, if there is not I will code it myself.

I can wager that it would not be able to parse stuff like Sin(90) on its own, and I understand that would need to be replaced by Math.Sin(90).

If there is a built in method, how do you use it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

浸婚纱 2024-08-12 18:17:30

通过使用 DataTable.Compute 方法。显然,这并不健壮(功能有限),并且出于此目的滥用 DataTable 感觉很黑客,但我想我会添加到当前的答案中。

示例:

var result = new DataTable().Compute("3+(7/3.5)", null); // 5

“Sin(90)”不适用于此方法。请参阅 DataColumn.Expression 属性页有关受支持函数的列表,特别是在“聚合”部分下。

使用 System.CodeDom 命名空间是一种选择。

一些有用的链接:


编辑: 在此发表您的评论是一种演示用等效的 Math 类方法替换三角函数的方法。

C#

string expression = "(Sin(0) + Cos(0)+Tan(0)) * 10";
string updatedExpression = Regex.Replace(expression, @"(?<func>Sin|Cos|Tan)\((?<arg>.*?)\)", match =>
            match.Groups["func"].Value == "Sin" ? Math.Sin(Int32.Parse(match.Groups["arg"].Value)).ToString() :
            match.Groups["func"].Value == "Cos" ? Math.Cos(Int32.Parse(match.Groups["arg"].Value)).ToString() :
            Math.Tan(Int32.Parse(match.Groups["arg"].Value)).ToString()
        );
var result = new DataTable().Compute(updatedExpression, null); // 10

VB.NET

Dim expression As String = "(Sin(0) + Cos(0)+Tan(0)) * 10"
Dim updatedExpression As String = Regex.Replace(expression, "(?<func>Sin|Cos|Tan)\((?<arg>.*?)\)", Function(match As Match) _
        If(match.Groups("func").Value = "Sin", Math.Sin(Int32.Parse(match.Groups("arg").Value)).ToString(), _
        If(match.Groups("func").Value = "Cos", Math.Cos(Int32.Parse(match.Groups("arg").Value)).ToString(), _
        Math.Tan(Int32.Parse(match.Groups("arg").Value)).ToString())) _
        )
Dim result = New DataTable().Compute(updatedExpression, Nothing)

但请注意,您需要知道“arg”组的内容。我知道它们是整数,所以我对它们使用了 Int32.Parse 。如果它们是项目的组合,那么这种简单的方法将不起作用。我怀疑如果解决方案因更多不受支持的函数调用而变得过于复杂,您将不断需要对解决方案进行创可贴,在这种情况下,CodeDom 方法或其他方法可能更合适。

There's a shortcut for limited (ie. simple) math expressions by using the DataTable.Compute method. Obviously, this isn't robust (limited functionality) and feels hackish to misuse the DataTable for this purpose, but I figured I would add to the current answers.

Example:

var result = new DataTable().Compute("3+(7/3.5)", null); // 5

"Sin(90)" wouldn't work with this approach. Refer to the DataColumn.Expression Property page for a list of supported functions, specifically under the "Aggregates" section.

Using the System.CodeDom namespace is an option.

Some helpful links:


EDIT: to address your comment, here is an approach to demonstrate replacing trigonometric functions with their equivalent Math class methods.

C#

string expression = "(Sin(0) + Cos(0)+Tan(0)) * 10";
string updatedExpression = Regex.Replace(expression, @"(?<func>Sin|Cos|Tan)\((?<arg>.*?)\)", match =>
            match.Groups["func"].Value == "Sin" ? Math.Sin(Int32.Parse(match.Groups["arg"].Value)).ToString() :
            match.Groups["func"].Value == "Cos" ? Math.Cos(Int32.Parse(match.Groups["arg"].Value)).ToString() :
            Math.Tan(Int32.Parse(match.Groups["arg"].Value)).ToString()
        );
var result = new DataTable().Compute(updatedExpression, null); // 10

VB.NET

Dim expression As String = "(Sin(0) + Cos(0)+Tan(0)) * 10"
Dim updatedExpression As String = Regex.Replace(expression, "(?<func>Sin|Cos|Tan)\((?<arg>.*?)\)", Function(match As Match) _
        If(match.Groups("func").Value = "Sin", Math.Sin(Int32.Parse(match.Groups("arg").Value)).ToString(), _
        If(match.Groups("func").Value = "Cos", Math.Cos(Int32.Parse(match.Groups("arg").Value)).ToString(), _
        Math.Tan(Int32.Parse(match.Groups("arg").Value)).ToString())) _
        )
Dim result = New DataTable().Compute(updatedExpression, Nothing)

Note, however, that you need to know the contents of the "arg" group. I know they are ints, so I used Int32.Parse on them. If they are a combination of items then this simple approach won't work. I suspect you will constantly need to band-aid the solution if it gets too complicated with more unsupported function calls, in which case the CodeDom approach or others may be more suitable.

凑诗 2024-08-12 18:17:30

这是一种我在其他地方没有提到过的计算表达式的方法:使用 WebBrowser 控件和 JavaScript 的 eval()

Option Strict On

Imports System.Security.Permissions

<PermissionSet(SecurityAction.Demand, Name:="FullTrust")> _
<System.Runtime.InteropServices.ComVisibleAttribute(True)>
Public Class Form1
    Dim browser As New WebBrowser

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        browser.ObjectForScripting = Me
        'browser.ScriptErrorsSuppressed = True
        browser.DocumentText = "<script>function evalIt(x) { return eval(x); }</script>"
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

        Dim result = browser.Document.InvokeScript("evalIt", New String() {"3+4*5"})
        If result IsNot Nothing Then
            MessageBox.Show(result.ToString())     '23
        End If
    End Sub
End Class

Here is a way to evaluate an expression that I haven't seen mentioned anywhere else: use a WebBrowser control and JavaScript's eval():

Option Strict On

Imports System.Security.Permissions

<PermissionSet(SecurityAction.Demand, Name:="FullTrust")> _
<System.Runtime.InteropServices.ComVisibleAttribute(True)>
Public Class Form1
    Dim browser As New WebBrowser

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        browser.ObjectForScripting = Me
        'browser.ScriptErrorsSuppressed = True
        browser.DocumentText = "<script>function evalIt(x) { return eval(x); }</script>"
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

        Dim result = browser.Document.InvokeScript("evalIt", New String() {"3+4*5"})
        If result IsNot Nothing Then
            MessageBox.Show(result.ToString())     '23
        End If
    End Sub
End Class
沙与沫 2024-08-12 18:17:30

这篇 CodeProject 文章可能会解决这个问题:

用 VB.NET 编写的表达式计算器
http://www.codeproject.com/KB/vb/expression_evaluator.aspx

还有这个:
http://www.dotnetspider.com/resources/ 2518-数学表达式-表达式-求值-VB.aspx

This CodeProject article might do the trick:

An expression evaluator written in VB.NET
http://www.codeproject.com/KB/vb/expression_evaluator.aspx

There is also this:
http://www.dotnetspider.com/resources/2518-mathematical-expression-expression-evaluate-VB.aspx

携君以终年 2024-08-12 18:17:30

一种方法是使用 CodeDom 命名空间来编译它并使用反射执行它。我不知道,可能没有那么高效。

One way would be to use the CodeDom namespace to compile it and execute it using reflection. May not be that performant, I don't know.

月亮是我掰弯的 2024-08-12 18:17:30

有点晚了,但这正是您想要的(确保解析输入以确保其中没有类似“something + vbcrlf + exec“format c:””的语句):

用法:

MessageBox.Show(COR.Tools.EvalProvider.Eval("return 8-3*2").ToString())

 
班级:

'Imports Microsoft.VisualBasic
Imports System


Namespace COR.Tools


Public Class EvalProvider


    Public Shared Function Eval(ByVal vbCode As String) As Object
        Dim c As VBCodeProvider = New VBCodeProvider
        Dim icc As System.CodeDom.Compiler.ICodeCompiler = c.CreateCompiler()
        Dim cp As System.CodeDom.Compiler.CompilerParameters = New System.CodeDom.Compiler.CompilerParameters

        cp.ReferencedAssemblies.Add("System.dll")
        cp.ReferencedAssemblies.Add("System.xml.dll")
        cp.ReferencedAssemblies.Add("System.data.dll")
        ' Sample code for adding your own referenced assemblies
        'cp.ReferencedAssemblies.Add("c:\yourProjectDir\bin\YourBaseClass.dll")
        'cp.ReferencedAssemblies.Add("YourBaseclass.dll")
        cp.CompilerOptions = "/t:library"
        cp.GenerateInMemory = True
        Dim sb As System.Text.StringBuilder = New System.Text.StringBuilder("")
        sb.Append("Imports System" & vbCrLf)
        sb.Append("Imports System.Xml" & vbCrLf)
        sb.Append("Imports System.Data" & vbCrLf)
        sb.Append("Imports System.Data.SqlClient" & vbCrLf)
        sb.Append("Imports Microsoft.VisualBasic" & vbCrLf)

        sb.Append("Namespace MyEvalNamespace  " & vbCrLf)
        sb.Append("Class MyEvalClass " & vbCrLf)

        sb.Append("public function  EvalCode() as Object " & vbCrLf)
        'sb.Append("YourNamespace.YourBaseClass thisObject = New YourNamespace.YourBaseClass()")
        sb.Append(vbCode & vbCrLf)
        sb.Append("End Function " & vbCrLf)
        sb.Append("End Class " & vbCrLf)
        sb.Append("End Namespace" & vbCrLf)
        Debug.WriteLine(sb.ToString()) ' look at this to debug your eval string
        Dim cr As System.CodeDom.Compiler.CompilerResults = icc.CompileAssemblyFromSource(cp, sb.ToString())
        Dim a As System.Reflection.Assembly = cr.CompiledAssembly
        Dim o As Object
        Dim mi As System.Reflection.MethodInfo
        o = a.CreateInstance("MyEvalNamespace.MyEvalClass")
        Dim t As Type = o.GetType()
        mi = t.GetMethod("EvalCode")
        Dim s As Object
        s = mi.Invoke(o, Nothing)
        Return s
    End Function


End Class ' EvalProvider


End Namespace

It's a bit late, but here is exactly what you wanted (make sure you parse the input to make sure there is no statement like 'something + vbcrlf + exec "format c:"' in it):

Usage:

MessageBox.Show(COR.Tools.EvalProvider.Eval("return 8-3*2").ToString())

 
Class:

'Imports Microsoft.VisualBasic
Imports System


Namespace COR.Tools


Public Class EvalProvider


    Public Shared Function Eval(ByVal vbCode As String) As Object
        Dim c As VBCodeProvider = New VBCodeProvider
        Dim icc As System.CodeDom.Compiler.ICodeCompiler = c.CreateCompiler()
        Dim cp As System.CodeDom.Compiler.CompilerParameters = New System.CodeDom.Compiler.CompilerParameters

        cp.ReferencedAssemblies.Add("System.dll")
        cp.ReferencedAssemblies.Add("System.xml.dll")
        cp.ReferencedAssemblies.Add("System.data.dll")
        ' Sample code for adding your own referenced assemblies
        'cp.ReferencedAssemblies.Add("c:\yourProjectDir\bin\YourBaseClass.dll")
        'cp.ReferencedAssemblies.Add("YourBaseclass.dll")
        cp.CompilerOptions = "/t:library"
        cp.GenerateInMemory = True
        Dim sb As System.Text.StringBuilder = New System.Text.StringBuilder("")
        sb.Append("Imports System" & vbCrLf)
        sb.Append("Imports System.Xml" & vbCrLf)
        sb.Append("Imports System.Data" & vbCrLf)
        sb.Append("Imports System.Data.SqlClient" & vbCrLf)
        sb.Append("Imports Microsoft.VisualBasic" & vbCrLf)

        sb.Append("Namespace MyEvalNamespace  " & vbCrLf)
        sb.Append("Class MyEvalClass " & vbCrLf)

        sb.Append("public function  EvalCode() as Object " & vbCrLf)
        'sb.Append("YourNamespace.YourBaseClass thisObject = New YourNamespace.YourBaseClass()")
        sb.Append(vbCode & vbCrLf)
        sb.Append("End Function " & vbCrLf)
        sb.Append("End Class " & vbCrLf)
        sb.Append("End Namespace" & vbCrLf)
        Debug.WriteLine(sb.ToString()) ' look at this to debug your eval string
        Dim cr As System.CodeDom.Compiler.CompilerResults = icc.CompileAssemblyFromSource(cp, sb.ToString())
        Dim a As System.Reflection.Assembly = cr.CompiledAssembly
        Dim o As Object
        Dim mi As System.Reflection.MethodInfo
        o = a.CreateInstance("MyEvalNamespace.MyEvalClass")
        Dim t As Type = o.GetType()
        mi = t.GetMethod("EvalCode")
        Dim s As Object
        s = mi.Invoke(o, Nothing)
        Return s
    End Function


End Class ' EvalProvider


End Namespace
塔塔猫 2024-08-12 18:17:30

我不知道内置的 VB.net,但我们通过链接 IronPython 运行时并向其传递表达式来完成类似的操作。这比使用反射要快得多。

I don't know about VB.net built in, but we do stuff like this by linking in the IronPython runtime and passing it the expressions. This is way way faster that using reflection.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文