前段時間朋友問我.NET有沒有一種動態編譯字符串的方式,遂寫了個Demo 如下:
using System;
#region Using Compiler
using Microsoft.CSharp;
using System.CodeDom.Compiler;
using System.Reflection;
#endregion
namespace Ahoo.Demo.DynamicCompiler
{
class Program
{
static void Main(string[] args)
{
CSharpCodeProvider csCoderPro = new CSharpCodeProvider();
CompilerParameters comParams = new CompilerParameters();
comParams.ReferencedAssemblies.Add("System.dll");
comParams.GenerateExecutable = false;
comParams.GenerateInMemory = true;
CompilerResults comResult = csCoderPro.CompileAssemblyFromSource(comParams, GetCode());
if (comResult.Errors.HasErrors)
{
Console.WriteLine("編譯異常!");
return;
}
Assembly objAssembly = comResult.CompiledAssembly;
object objHW = objAssembly.CreateInstance("Ahoo.Demo.DynamicCompiler.HelloWorld");
MethodInfo objMI = objHW.GetType().GetMethod("Hello");
objMI.Invoke(objHW, null);
Console.ReadLine();
}
public static String GetCode()
{
return
"using System;" +
"namespace Ahoo.Demo.DynamicCompiler" +
"{" +
"public class HelloWorld" +
"{" +
"public void Hello()" +
"{" +
"Console.WriteLine(\"" + "Hello World!" + "\");" +
"}" +
"}" +
"}";
}
}
}