首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> 關於ASP.NET

善用 CodeDom 與反射:動態編譯組件並即時執行

     編輯:關於ASP.NET

動態編譯步驟

  1. 取得編譯器:ICodeCompiler compiler = new CSharpCodeProvider().CreateCompiler();
  2. 設定參數:參考組件 (System.dll 等)、輸出為記憶體內 DLL (GenerateInMemory=true)。
  3. 建構原始碼字串 (StringBuilder)。
  4. compiler.CompileAssemblyFromSource(cp, source) 編譯。
  5. result.CompiledAssembly.CreateInstance("MyClass") 建立實例。
  6. 反射呼叫方法:method.Invoke(instance, null)。

完整範例

StringBuilder sb = new StringBuilder();
sb.Append("using System; ");
sb.Append("public class MyClass { public string HelloWorld() { return \"Hello,world\"; } }");
CompilerResults result = compiler.CompileAssemblyFromSource(cp, sb.ToString());
object obj = result.CompiledAssembly.CreateInstance("MyClass");
MethodInfo mi = obj.GetType().GetMethod("HelloWorld");
Console.WriteLine(mi.Invoke(obj, null)); // 輸出 Hello,world

適用場景:依資料庫結構動態生成實體類別、規則引擎、腳本化擴充。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved