Evaluate an arithmetic expression stored in a string (C #)

I am working on a C # application in which I want to evaluate an arithmetic expression that is given as a string. So how did I get the line:

string myExpr="4*(80+(5/2))+2";

And I want to calculate the result of an arithmetic expression. Although in a language such as Javascript, PHP, etc., you could just use Eval to do the trick, which doesn't seem to be an option in C #.

I believe that you can write code to divide it into countless simple expressions, calculate them and add them together, but it will take quite a while and I will probably have a lot of problems in my attempt to do this.

So ... my question is: is there a "simple" way to do this?

+5
source share
9 answers

javascript, , - :

var engine = VsaEngine.CreateEngine();
Eval.JScriptEvaluate(mySum, engine);

; - Microsoft.JScript

+5

JScript.NET eval. .NET .

+5

http://ncalc.codeplex.com?

, (, ) , EvaluateFunction/EvaluateParameter. , :

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());

unicode . antler, . , MEF .

, / if.

+5
+3

NCalc . . , , :

string myExpr = "4*(80+(5/2))+2";
decimal result = Convert.ToDecimal(new Expression(myExpr).Evaluate());
+2

. , , "". Eval ; , , #.

" " " ", .

0

Bjarne Stroustrup ++, 6 ( ++), , .

, , .

0

- undergrad,

#

.

Reverse Polish Notation, . , . .

0

- :

int mySum = 4*(80+(5/2))+2;

var myStringSum = mySum.toString();
-1

All Articles