Is there a string math evaluator in .NET?

前端 未结 16 1407
长情又很酷
长情又很酷 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:18

    Have you seen http://ncalc.codeplex.com ?

    It's extensible, fast (e.g. has its own cache) enables you to provide custom functions and varaibles at run time by handling EvaluateFunction/EvaluateParameter events. Example expressions it can parse:

    Expression e = new Expression("Round(Pow(Pi, 2) + Pow([Pi2], 2) + X, 2)"); 
    
      e.Parameters["Pi2"] = new Expression("Pi * Pi"); 
      e.Parameters["X"] = 10; 
    
      e.EvaluateParameter += delegate(string name, ParameterArgs args) 
        { 
          if (name == "Pi") 
          args.Result = 3.14; 
        }; 
    
      Debug.Assert(117.07 == e.Evaluate()); 
    

    It also handles unicode & many data type natively. It comes with an antler file if you want to change the grammer. There is also a fork which supports MEF to load new functions.

提交回复
热议问题