Is there a string math evaluator in .NET?

前端 未结 16 1421
长情又很酷
长情又很酷 2020-11-22 01:01

If I have a string with a valid math expression such as:

String s = \"1 + 2 * 7\";

Is there a built in library/function in .NET that will p

16条回答
  •  广开言路
    2020-11-22 01:26

    You could add a reference to Microsoft Script Control Library (COM) and use code like this to evaluate an expression. (Also works for JScript.)

    Dim sc As New MSScriptControl.ScriptControl()
    sc.Language = "VBScript"
    Dim expression As String = "1 + 2 * 7"
    Dim result As Double = sc.Eval(expression)
    

    Edit - C# version.

    MSScriptControl.ScriptControl sc = new MSScriptControl.ScriptControl();
    sc.Language = "VBScript";
    string expression = "1 + 2 * 7";
    object result = sc.Eval(expression);            
    MessageBox.Show(result.ToString());
    

    Edit - The ScriptControl is a COM object. In the "Add reference" dialog of the project select the "COM" tab and scroll down to "Microsoft Script Control 1.0" and select ok.

提交回复
热议问题