zoukankan      html  css  js  c++  java
  • (论坛答疑点滴)一个动态编译的例子

    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("1+2*3");
       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;

      }

     }
    }

  • 相关阅读:
    小、快、简、易、强的“银弹”— fastm
    使用Creative suite 3和Flex Builder3实现Flex 3的换肤
    Apache HTTP Server 与 Tomcat 的三种连接方式介绍
    iframe自动适应付窗口的大小变换
    Flash网络游戏开发入门经验共享
    比较详细的 Linux Top 命令解析
    HttpContext是干什么的
    asp.net,cookie,写cookie,取cookie 的方法
    为什么我们不要 .NET 程序员
    在Ubuntu上安装使用深度影音&深度音乐(推荐)
  • 原文地址:https://www.cnblogs.com/lovecherry/p/125520.html
Copyright © 2011-2022 走看看