Need a formula interpreter for .Net [closed]

爷,独闯天下 提交于 2019-12-05 07:21:45

A couple I've used in the past with no problems:

You can actually build a very effective interpreter by parsing and replacing certain functional keywords such as max with Math.Max and then dynamically building and executing the formula as a C# class and method. So actually you would be parsing and wrapping the formula and allowing the C# compiler to interpret and execute it.

So, taking your sample formula of max(1+2, 4) * x would turn into:

public class MyFormula
{
    public double calc(double x)
    {
        return Math.Max(1+2, 4) * x;
    }
}

Which you would compile on the fly and then execute per the linked article. You still have to parse for and pass the x value of course.

A long time ago in one project i had to create some booking with formulas, and i used VsaEngine. To use this engine you need to add reference to Microsoft.JScript. Here is example:

Code for usage is very simple, just replace formula parameters like:

string formula = "x+y";
formula=  formula.Replace("x","100").Replace("y","200");
string result = CalculateFormula(formula);

And here is core method, CalculateFormula:

public string CalculateFormula(string evaluationString)
{ 
      VsaEngine en = VsaEngine.CreateEngine();
      Object result = Eval.JScriptEvaluate(evaluationString, en);
      return result.ToString();
}

With this you can create your custom formula interpreter engine.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!