如题?

解决方案 »

  1.   

    using System;
    using System.CodeDom.Compiler;
    using Microsoft.CSharp;
    using System.Reflection;
    using System.Text;namespace ConsoleApplication22
    {
     /// <summary>
     /// Class1 的摘要说明。
     /// </summary>
     class Class1
     {
      /// <summary>
      /// 应用程序的主入口点。
      /// </summary>
      [STAThread]
      static void Main(string[] args)
      {
       //
       // TODO: 在此处添加代码以启动应用程序
       //
       int i = (int)Calc("20*10+5*20");
       Console.WriteLine(i.ToString());
       Console.ReadLine();  }  public  static  object  Calc(string  expression)  
      {  
       string  className  =  "Calc";  
       string  methodName  =  "Run";  
       expression=expression.Replace("/","*1.0/");
                             
       //  创建编译器实例。  
       ICodeCompiler  complier  =  (new  CSharpCodeProvider().CreateCompiler());  
       //  设置编译参数。  
       CompilerParameters  paras  =  new  CompilerParameters();  
       paras.GenerateExecutable  =  false;  
       paras.GenerateInMemory  =  true;  
     
       //  创建动态代码。  
       StringBuilder  classSource  =  new  StringBuilder();    
       classSource.Append("public  class  "+  className  +"\n");  
       classSource.Append("{\n");  
       classSource.Append("        public  object  "  +  methodName  +  "()\n");  
       classSource.Append("        {\n");  
       classSource.Append("                return  "+  expression  +  ";\n");  
       classSource.Append("        }\n");  
       classSource.Append("}");  
     
       //System.Diagnostics.Debug.WriteLine(classSource.ToString());  
     
       //  编译代码。  
       CompilerResults  result  =  complier.CompileAssemblyFromSource(paras,  classSource.ToString());  
                             
       //  获取编译后的程序集。  
       Assembly  assembly  =  result.CompiledAssembly;  
       
       //  动态调用方法。  
       object  eval  =  assembly.CreateInstance(className);  
       MethodInfo  method  =  eval.GetType().GetMethod(methodName);  
       object reobj = method.Invoke(eval,  null);  
       GC.Collect();
       return reobj;  } }
    }
      

  2.   

    LoveCherry(论成败,人生豪迈;大不了,重头再来!^_^) :
    =============
    谢谢,我试试多。
      

  3.   

    OK,谢谢LoveCherry(论成败,人生豪迈;大不了,重头再来!^_^) 结贴。
      

  4.   

    int i = (int)Calc("20*10+5*20");保存一下先