所謂動態代碼執行,和指令碼引擎有點類似。就是程式執行期從字串或者文字檔中讀取一段 C# 代碼,在記憶體中動態編譯成程式集,並建立相互關聯類型執行個體執行相關方法。
具體的實現可參考下面的代碼。如需要產生組件檔,可參考《使用CodeDom產生程式集》。
using System;
using System.Reflection;
using System.Globalization;
using Microsoft.CSharp;
using System.CodeDom;
using System.CodeDom.Compiler;
namespace ConsoleApplication1
{
public class Program
{
static void Main(string[] args)
{
// 定義需要動態執行的 C# 代碼字串,當然也可從文字檔中讀取。
string code = @"
using System;
namespace MyNamespace
{
public class MyClass
{
private string name;
public MyClass(string name)
{
this.name = name;
}
public void Test()
{
Console.WriteLine(""{0} - {1}"", name, DateTime.Now);
}
}
}
";
// 建立編譯器對象
CSharpCodeProvider p = new CSharpCodeProvider();
ICodeCompiler cc = p.CreateCompiler();
// 設定編譯參數
CompilerParameters options = new CompilerParameters();
options.ReferencedAssemblies.Add("System.dll");
options.GenerateInMemory = true;
options.OutputAssembly = "MyTest";
// 開始編譯
CodeSnippetCompileUnit cu = new CodeSnippetCompileUnit(code);
CompilerResults cr = cc.CompileAssemblyFromDom(options, cu);
// 執行動態程式集相關內容。DW&Q供^U3Oq理:N`K9)y;8中1XX^4`#教管o,N3專qQIC3-垠O育bH
3H+o管&Ich理&-Y
Type t = cr.CompiledAssembly.GetType("MyNamespace.MyClass");
object o = cr.CompiledAssembly.CreateInstance("MyNamespace.MyClass", false, BindingFlags.Default,
null, new object[] { "Tom" }, CultureInfo.CurrentCulture, null);
t.InvokeMember("Test", BindingFlags.Instance | BindingFlags.Public | BindingFlags.InvokeMethod,
null, o, null);
}
}
}
轉載