In actual development, it is sometimes necessary according to the formula made according to the user and then processes the value of this formula, because the value is replaced by the parameters, because it is just to do this, I have read some information, so I wrote a class call to implement this function.
Using system; using system.codedom.compiler; using microsoft.csharp; using system.reflection;
PUBLIC CLASS EVALUATOR {Object_compiled = NULL;
PRIVATE STRING M_FORMULA;
///
Public evatarator () {}
Public Evaluator (String Formula) {Formula = Formula;
Public double execute () {if (formula == null || formula == ") {throw new exception (" Please set the formula attribute! ");} returnid (Formula);} public double execute formula) {constructEvaluator (formula);. MethodInfo m = _compiled.GetType () GetMethod ( "GetValue"); return (Double) m.Invoke (_compiled, null);} private void constructEvaluator (string formula) {ICodeCompiler compiler = ( New csharpcodeProvider (). CreateCompiler (); CompilerParameters cp = new compilerParameters (); cp.referenceDassemblies.add ("system.dll");
Cp.GenerateExecutable = false; cp.generateinMemory = true;
Stringbuilder str = new stringbuilder (); str.append ("using system; / n"); str.append ("namespace stoway {/ n"); str.append ("Public Class Formula {/ N");
Str.Appendformat ("public {0} getValue ()", "double"); str.append ("{"); str.appendformat ("Return Convert.Todouble;", Formula); STR. Append ("} / n"); str.append ("} / n"); str.append ("}");
CompilerResults cr = compiler.CompileAssemblyFromSource (cp, str.ToString ()); if (cr.Errors.HasErrors) {throw new Exception ( "not correct expressions");} Assembly a = cr.CompiledAssembly; _compiled = a. CreateInstance ("stoway.formula");} public static double getValue (string formula) {return new evatarator (). Execute (formula);}} ----------- Call method: evalent EVALUATOR = New Evaluator (); double number ("(" ("(3 5) * 2 56 / 0.25"); Double Num = EVALUATOR.GETVALUE ("(3 5) * 2 56 / 0.25") ; ------------------------------------------------- --------
Related: http://www.codeproject.com/csharp/matheval.asphttp://www.codeproject.com/csharp/runtime_eval.asp