C#动态编译、执行代码

C#动态编译、执行代码

Compiling and Running code at runtime

<script type="text/javascript"> </script> <script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script>

.NET Framework 提供了使您以编程方式访问 C# 语言编译器的类。 这使我们能编写自己的代码编译实用程序。 本文提供了示例代码,演示了如何使用C#在运行时动态编译,执行代码。


  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.CodeDom.Compiler;
  5. using System.IO;
  6. using Microsoft.CSharp;
  7. using System.Reflection;

  8. namespace DynaCode
  9. {
  10.     class Program
  11.     {
  12.         static string[] code = {
  13.             "using System;"+
  14.             "namespace DynaCode"+
  15.             "{"+
  16.             "   public class HelloWorld"+
  17.             "   {"+
  18.             "       static public int Main(string str)"+
  19.             "       {"+
  20.             "           return str.Length;"+
  21.             "       }"+
  22.             "   }"+
  23.             "}"};

  24.         static void Main(string[] args)
  25.         {
  26.             CompileAndRun(code);
  27.             Console.ReadKey();
  28.         }

  29.         static void CompileAndRun(string[] code)
  30.         {
  31.             //通过使用 CompilerParameters 类,会将参数传递给编译器
  32.             CompilerParameters CompilerParams = new CompilerParameters();
  33.             string outputDirectory = Directory.GetCurrentDirectory();

  34.             CompilerParams.GenerateInMemory = true;
  35.             CompilerParams.TreatWarningsAsErrors = false;
  36.             CompilerParams.GenerateExecutable = false;
  37.             CompilerParams.CompilerOptions = "/optimize";

  38.             string[] references = { "System.dll" };
  39.             CompilerParams.ReferencedAssemblies.AddRange(references);
  40.            
  41.             //CSharpCodeProvider提供在C# 代码生成器和代码编译器的实例的访问
  42.             CSharpCodeProvider provider = new CSharpCodeProvider();

  43.             //CompileAssemblyFromSource使用指定的编译器,从包含源代码的字符串设置编译程序集
  44.             CompilerResults compile = provider.CompileAssemblyFromSource(CompilerParams, code);

  45.             if (compile.Errors.HasErrors)
  46.             {
  47.                 string text = "Compile error: ";
  48.                 foreach (CompilerError ce in compile.Errors)
  49.                 {
  50.                     text += "rn" + ce.ToString();
  51.                 }
  52.                 throw new Exception(text);
  53.             }

  54.         
  55.             //ExpoloreAssembly(compile.CompiledAssembly);
  56.             Module module = compile.CompiledAssembly.GetModules()[0];
  57.             Type mt = null;
  58.             MethodInfo methInfo = null;
  59.             if (module != null)
  60.             {
  61.                 mt = module.GetType("DynaCode.HelloWorld");
  62.             }
  63.             if (mt != null)
  64.             {
  65.                 methInfo = mt.GetMethod("Main");
  66.             }
  67.             if (methInfo != null)
  68.             {
  69.                 Console.WriteLine(methInfo.Invoke(nullnew object[] { "here in dyna code" }));
  70.             }
  71.         }

  72.         static void ExpoloreAssembly(Assembly assembly)
  73.         {
  74.             Console.WriteLine("Modules in the assembly:");
  75.             foreach (Module m in assembly.GetModules())
  76.             {
  77.                 Console.WriteLine("{0}", m);
  78.                 foreach (Type t in m.GetTypes())
  79.                 {
  80.                     Console.WriteLine("t{0}", t.Name);
  81.                     foreach (MethodInfo mi in t.GetMethods())
  82.                     {
  83.                         Console.WriteLine("tt{0}", mi.Name);
  84.                     }
  85.                 }
  86.             }
  87.         }
  88.     }
  89. }
Dynamically Compiling C#
Dynamically executing code in .Net.
<script type="text/javascript"> </script> <script src="http://pagead2.googlesyndication.com/pagead/show_ads.js" type="text/javascript"> </script>
How to programmatically compile code using C# compiler
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值