1、簡介
能夠動態執行 C# 代碼是一件很酷的功能,比如,我們可以在控制台中輸入一行 C# 代碼,然後程序 自動編譯並執行這一行代碼,將結果顯示給我們。這差不多就是一個最簡單的 C# 代碼解釋器了。
動態執行 C# 代碼又是一件很有用的功能,比如,我們可以將某些代碼寫在某個文件之中,由程序集 在執行時進行加載,改變這些代碼不用中止程序,當程序再次加載這些代碼時,就自動執行的是新代碼了 。
下面,我將在寫一個簡單C# 代碼解釋器,然後將在 C# 代碼解釋器之中加入動態代碼與解釋器環境間 的動態交互機制,來演示一個很好很強大的應用。
2、簡單的 C# 代碼解釋器
關於如何動態執行 C# 代碼在 Jailu.Net 的《如何用C#動態編譯、執行代碼》一文中講述的很清晰。 采用該文所述方式寫一個 C# 代碼解釋器:
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Globalization;
using Microsoft.CSharp;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Text;
using System.IO;
using System.XML;
namespace Test
{
class Program
{
static void Main(string[] args)
{
Console.Write(">> ");
String cmd;
Context cxt = new Context();
while ((cmd = Console.ReadLine().Trim()) != "exit")
{
if (!String.IsNullOrEmpty(cmd))
{
Console.WriteLine();
cxt.Invoke(cmd);
}
Console.Write("\n>> ");
}
}
}
public class Context
{
public CSharpCodeProvider CodeProvider { get; set; }
public IDictionary<String, Assembly> Assemblys { get; set; }
public Context()
{
CodeProvider = new CSharpCodeProvider(new Dictionary<string, string>() { { "CompilerVersion", "v3.5" } });
Assemblys = new Dictionary<String, Assembly>();
Assembly[] al = AppDomain.CurrentDomain.GetAssemblIEs();
foreach (Assembly a in al)
{
AddAssembly(a);
}
AppDomain.CurrentDomain.AssemblyLoad += new AssemblyLoadEventHandler (CurrentDomain_AssemblyLoad);
}
private void AddAssembly(Assembly a)
{
if (a != null)
{
Assemblys.Add(a.FullName, a);
}
}
void CurrentDomain_AssemblyLoad(object sender, AssemblyLoadEventArgs args)
{
Assembly a = args.LoadedAssembly;
if (!Assemblys.ContainsKey(a.FullName))
{
AddAssembly(a);
}
}
public CompilerParameters CreateCompilerParameters()
{
CompilerParameters cp = new CompilerParameters();
cp.GenerateExecutable = false;
cp.GenerateInMemory = true;
if (Assemblys != null)
{
foreach (Assembly a in Assemblys.Values)
{
cp.ReferencedAssemblIEs.Add(a.Location);
}
}
return cp;
}
public void Invoke(String cmd)
{
String inputCmdString = cmd.Trim();
if (String.IsNullOrEmpty(inputCmdString)) return;
String fullCmd = BuildFullCmd(inputCmdString);
CompilerResults cr = CodeProvider.CompileAssemblyFromSource (CreateCompilerParameters(), fullCmd);
if (cr.Errors.HasErrors)
{
Boolean recompileSwitch = true;
foreach (CompilerError err in cr.Errors)
{
//CS0201 : Only assignment, call, increment, decrement, and new object expressions can be
//used as a statement
if (!err.ErrorNumber.Equals("CS0201"))
{
recompileSwitch = false;
break;
}
}
// 重新編譯
if (recompileSwitch)
{
String dynaName = "TempArg_Dynamic_" + DateTime.Now.Ticks.ToString ();
inputCmdString = String.Format(" var {0} = ", dynaName) + inputCmdString;
inputCmdString += ";\n System.Console.WriteLine(" + dynaName + ");";
fullCmd = BuildFullCmd(inputCmdString);
cr = CodeProvider.CompileAssemblyFromSource(CreateCompilerParameters (), fullCmd);
}
if (cr.Errors.HasErrors)
{
Console.WriteLine("編譯錯誤:");
foreach (CompilerError err in cr.Errors)
{
Console.WriteLine(err.ErrorNumber);
Console.WriteLine(err.ErrorText);
}
return;
}
}
Assembly assem = cr.CompiledAssembly;
Object dynamicObject = assem.CreateInstance("Test.DynamicClass");
Type t = assem.GetType("Test.DynamicClass");
MethodInfo minfo = t.GetMethod("MethodInstance");
minfo.Invoke(dynamicObject, null);
}
private String BuildFullCmd(String inputCmdString)
{
String fullCmd = String.Empty;
fullCmd += @"
namespace Test
{
public class DynamicClass
{
public void MethodInstance()
{
" + inputCmdString + @";
}
}
}";
return fullCmd;
}
}
}