C# 动态编译代码:
公共辅助类,有注释就不废话了。
using System; using System.Text; using System.Reflection; using System.CodeDom.Compiler; namespace DynamicCompilation.Compilation { /// /// 编译返回结果 /// public class CompilationReturn { /// /// 程序集 /// public Assembly Assembly { get; set; } /// /// 编译错误列表 /// public CompilerErrorCollection Errors { get; set; } /// /// 编译结果,如果编译成功Errors==null||编译失败Assembly==null /// public Boolean CompilationResults { get; set; } } } using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.CodeDom.Compiler; namespace DynamicCompilation.Compilation { /// /// C#源码操作,主要包括动态生成dll,动态加载dll /// public class SourceOperating { /// /// 动态编译C#代码,但不会保存dll到本地 /// /// 编译内容 /// 预先加载的dll /// 编译结果 public static CompilationReturn SourceCompiler(String strClass, params String[] dllParam) { return SourceCompiler(strClass, null, dllParam); } /// /// 动态编译C#代码 /// /// 编译内容 /// dll保持地址 /// 预先加载的dll /// 编译结果 public static CompilationReturn SourceCompiler(String strClass, String savePath, params String[] dllParam) { //设置需要编译的语言类型 CodeDomProvider _p = CodeDomProvider.CreateProvider("C#"); //编译参数对象 CompilerParameters parameter = new CompilerParameters(); //预先加载编译时需要的dll文件 foreach (String str in dllParam) { parameter.ReferencedAssemblies.Add(str); } //判断是否需要将dll文件保存到本地 if (!String.IsNullOrEmpty(savePath)) parameter.OutputAssembly = savePath; parameter.GenerateExecutable = false; parameter.GenerateInMemory = false; //dll编译 var _result = _p.CompileAssemblyFromSource(parameter, strClass); CompilationReturn result = null; if (_result.Errors.HasErrors) { //将错误抛出 return result = new CompilationReturn() { CompilationResults = false, Errors = _result.Errors }; } else { //将编译结果返回 return result = new CompilationReturn() { CompilationResults = true, Assembly = _result.CompiledAssembly }; } } } }
动态编译测试代码,这是一个文本文件:
using System; using System.Text; namespace DynamicCompilation { public class Code { public void Hello() { Console.WriteLine("这是动态编译出来的"); } } }
测试代码:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using DynamicCompilation.Compilation; namespace DynamicCompilation { class Program { static void Main(string[] args) { //读取需要编译的代码 StreamReader objReader = new StreamReader("Code.txt"); String code = objReader.ReadToEnd(); //动态编译 CompilationReturn result = SourceOperating.SourceCompiler(code, (new List() { "System.dll" }).ToArray()); if (!result.CompilationResults) { //编译出错 抛出编译错误信息 foreach (var error in result.Errors) { Console.WriteLine(error.ToString()); } } else { //实例化对象 dynamic obj = result.Assembly.CreateInstance("DynamicCompilation.Code"); //调用对象的方法 obj.Hello(); } } } }