//編譯引擎設計部分
using System;
using System.Text;
using System.CodeDom.Compiler;
using System.Reflection;
using Microsoft.CSharp;
namespace ToolPackages.CodeDomProvider
{
public class SampleCodeDomProvider
{
//代碼生成器對象
private static System.CodeDom.Compiler.CodeDomProvider comp = new CSharpCodeProvider();
//編譯器參數
private static CompilerParameters cp = new CompilerParameters();
private object curObj;
public bool Compile(string codes)
{
StringBuilder codeBuilder = new StringBuilder();
//完成待編譯的代碼構建工作,可移動到調用層構建
codeBuilder.Append("using System;");
codeBuilder.Append("using Microsoft.JScript;");
codeBuilder.Append("public class Sharpnessdotnet{");
codeBuilder.Append(codes);
codeBuilder.Append("}");
//完成編譯器參數的初始化
//1.引用的程序集
cp.ReferencedAssemblIEs.Add("System.dll");
cp.ReferencedAssemblIEs.Add("Microsoft.JScript.dll");
//2.僅在內存中生成
cp.GenerateExecutable = false;
cp.GenerateInMemory = true;
string code = codeBuilder.ToString();
//利用編譯器參數設置和構建的代碼進行編譯工作
CompilerResults cr = comp.CreateCompiler().CompileAssemblyFromSource(cp, code);
//判斷是否編譯成功
if (cr.Errors.HasErrors)
{
return false;
}
else
{
//獲取編譯成功的程序集
Assembly a = cr.CompiledAssembly;
//從程序集中獲取指定類型
System.Type type = a.GetType("Sharpnessdotnet");
//調用其默認構造函數,返回一個實例
curObj = type.GetConstructor(new Type[0]).Invoke(null);