用JScript加载动态编译与执行,不要想着加个 &符或者自己写编译器。在网上查JScript(注意,不是JavaScript),这方面资料很多的。

解决方案 »

  1.   

    自定义表达式解析类,参考这篇文章:http://community.csdn.net/Expert/FAQ/FAQ_Index.asp?id=115064
      

  2.   

    using System;
    using System.CodeDom.Compiler;
    using System.Reflection;
    using Microsoft.JScript;namespace OdeToCode.Utility
    {
       public class Evaluator
       {
          public static int EvalToInteger(string statement)
          {
             string s = EvalToString(statement);
             return int.Parse(s.ToString());
          }      public static double EvalToDouble(string statement)
          {
             string s = EvalToString(statement);
             return double.Parse(s);
          }      public static string EvalToString(string statement)
          {
             object o = EvalToObject(statement);
             return o.ToString();
          }      public static object EvalToObject(string statement)
          {
             return _evaluatorType.InvokeMember(
                         "Eval", 
                         BindingFlags.InvokeMethod, 
                         null, 
                         _evaluator, 
                         new object[] { statement } 
                      );
          }
                   
          static Evaluator()
          {
             ICodeCompiler compiler;
             compiler = new JScriptCodeProvider().CreateCompiler();         CompilerParameters parameters;
             parameters = new CompilerParameters();
             parameters.GenerateInMemory = true;
             
             CompilerResults results;
             results = compiler.CompileAssemblyFromSource(parameters, _jscriptSource);         Assembly assembly = results.CompiledAssembly;
             _evaluatorType = assembly.GetType("Evaluator.Evaluator");
             
             _evaluator = Activator.CreateInstance(_evaluatorType);
          }
          
          private static object _evaluator = null;
          private static Type _evaluatorType = null;
          private static readonly string _jscriptSource = 
             
              @"package Evaluator
                {
                   class Evaluator
                   {
                      public function Eval(expr : String) : String 
                      { 
                         return eval(expr); 
                      }
                   }
                }";
       }
    }
      

  3.   

    调用 
    int a=EvalToInteger("2*3+1");
    double b=EvalToDouble("2.5+3.3");
    string c=EvalToString("表达式") //可以计算真假之类的逻辑值