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#在运行时动态编译,执行代码。
- using System;
- using System.Collections.Generic;
- using System.Text;
- using System.CodeDom.Compiler;
- using System.IO;
- using Microsoft.CSharp;
- using System.Reflection;
- namespace DynaCode
- {
- class Program
- {
- static string[] code = {
- "using System;"+
- "namespace DynaCode"+
- "{"+
- " public class HelloWorld"+
- " {"+
- " static public int Main(string str)"+
- " {"+
- " return str.Length;"+
- " }"+
- " }"+
- "}"};
- static void Main(string[] args)
- {
- CompileAndRun(code);
- Console.ReadKey();
- }
- static void CompileAndRun(string[] code)
- {
- //通过使用 CompilerParameters 类,会将参数传递给编译器
- CompilerParameters CompilerParams = new CompilerParameters();
- string outputDirectory = Directory.GetCurrentDirectory();
- CompilerParams.GenerateInMemory = true;
- CompilerParams.TreatWarningsAsErrors = false;
- CompilerParams.GenerateExecutable = false;
- CompilerParams.CompilerOptions = "/optimize";
- string[] references = { "System.dll" };
- CompilerParams.ReferencedAssemblies.AddRange(references);
-
- //CSharpCodeProvider提供在C# 代码生成器和代码编译器的实例的访问
- CSharpCodeProvider provider = new CSharpCodeProvider();
- //CompileAssemblyFromSource使用指定的编译器,从包含源代码的字符串设置编译程序集
- CompilerResults compile = provider.CompileAssemblyFromSource(CompilerParams, code);
- if (compile.Errors.HasErrors)
- {
- string text = "Compile error: ";
- foreach (CompilerError ce in compile.Errors)
- {
- text += "rn" + ce.ToString();
- }
- throw new Exception(text);
- }
-
- //ExpoloreAssembly(compile.CompiledAssembly);
- Module module = compile.CompiledAssembly.GetModules()[0];
- Type mt = null;
- MethodInfo methInfo = null;
- if (module != null)
- {
- mt = module.GetType("DynaCode.HelloWorld");
- }
- if (mt != null)
- {
- methInfo = mt.GetMethod("Main");
- }
- if (methInfo != null)
- {
- Console.WriteLine(methInfo.Invoke(null, new object[] { "here in dyna code" }));
- }
- }
- static void ExpoloreAssembly(Assembly assembly)
- {
- Console.WriteLine("Modules in the assembly:");
- foreach (Module m in assembly.GetModules())
- {
- Console.WriteLine("{0}", m);
- foreach (Type t in m.GetTypes())
- {
- Console.WriteLine("t{0}", t.Name);
- foreach (MethodInfo mi in t.GetMethods())
- {
- Console.WriteLine("tt{0}", mi.Name);
- }
- }
- }
- }
- }
- }
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