1. Background
If a string expression is given"-12 * ( - 2.2 + 7.7 ) - 44 * 2"
, let you calculate the results, and those who are familiar with JavaScript know that there is aEval
Functions can be calculated directly, but this function is not available in C#. The following are three implementation methods
2. Code
public class Class1 { #region Method 1: Use CodeCom [Obsolete] comp = new ().CreateCompiler(); cp = new (); public object Eval_1(string Expression) { StringBuilder code = new StringBuilder(); ("using System; \n"); ("namespace ADOGuy { \n"); (" public class _Evaluator { \n"); (" public object __foo() "); ("{ "); (" return ({0}); ", Expression); ("}\n"); ("} }"); cr = (cp, ()); a = ; object _Compiled = ("ADOGuy._Evaluator"); mi = _Compiled.GetType().GetMethod("__foo"); return (_Compiled, null); } #endregion #region Method 2: Analysis of expressions string Precede(string p, string q) { switch (p) { case "+": case "-": return ("*/(".IndexOf(q) != -1) ? "<" : ">"; case "*": case "/": return (q == "(") ? "<" : ">"; case "(": return (q == ")") ? "=" : "<"; case ")": return (q == "(") ? "?" : ">"; case "#": return (q == "#") ? "=" : "<"; } return "?"; } Double Operate(Double a, char o, Double b) { switch (o) { case '+': return a + b; case '-': return a - b; case '*': return a * b; case '/': return a / b; } return 0; } public Object Eval_2(string Expression) { Stack nArr = new Stack(), oArr = new Stack(); int j = 0; Double a = 0, b = 0; string w = ""; char o; MatchCollection arr = ((" ", "") + "#", @"(((?<=(^|\())-)?\d+(\.\d+)?|\D)"); ('#'); w = (arr[j++]); while (!(w == "#" && (()) == "#")) { if ("+-*/()#".IndexOf(w) != -1) { switch (Precede(().ToString(), w)) { case "<": (w); w = (arr[j++]); break; case "=": (); w = (arr[j++]); break; case ">": o = (()); b = (()); a = (()); (Operate(a, o, b)); break; default: return "Error"; } } else { (w); w = (arr[j++]); } } return (); } #endregion #region Method 3: Eval using JScript // Requires a quote [Obsolete] readonly ve = (); [Obsolete] public object Eval_3(string Expression) { return (Expression, ve); } #endregion }
3. Test
static void Main(string[] args) { String strExpression = "-12 * ( - 2.2 + 7.7 ) - 44 * 2"; var obj = new Class1(); ($"Method 1(CodeComLaw)Calculation results:{obj.Eval_1(strExpression)}"); ($"方Law二(分析Law)Calculation results:{obj.Eval_2(strExpression)}"); ($"方Law三(JScriptLaw)Calculation results:{obj.Eval_3(strExpression)}"); (); }
Running results:
Method 1 (CodeCom method) calculation result: -154
Method 2 (analysis method) calculation result: -154
Method 3 (JScript method) calculation result: -154
The above is the detailed content of three methods of C# implementing Eval (string expression). For more information about C# implementing Eval (string expression) please pay attention to my other related articles!