C# 动态编译代码实现

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.CodeDom.Compiler; using Microsoft.CSharp; using System.Web; using System.Reflection; namespace VSOnline.Framework { /// <summary> /// 代码执行类 /// </summary> public class CodeRun { /// <summary> /// Framework版本,可选择v2.0, v3.0, v3.5 /// </summary> private string CompilerVersion { get; set; } /// <summary> /// 构造函数 /// </summary> /// <param name="compilerVersion">Framework版本,可选择v2.0, v3.0, v3.5</param> public CodeRun(string compilerVersion) { CompilerVersion = compilerVersion; } /// <summary> /// 构造函数,默认为3.5版本 /// </summary> public CodeRun() { CompilerVersion = "v3.5"; } /// <summary> /// 动态编译并执行代码 /// </summary> /// <param name="code">代码</param> /// <returns>返回输出内容</returns> public List<string> Run(string code, string id) { Consoler.Outputs.Add(id, new Consoler()); CompilerParameters compilerParams = new CompilerParameters(); //编译器选项设置 compilerParams.CompilerOptions = "/target:library /optimize"; //compilerParams.CompilerOptions += @" /lib:""C:/Program Files/Reference Assemblies/Microsoft/Framework/v3.5/"""; //编译时在内存输出 compilerParams.GenerateInMemory = true; //生成调试信息 compilerParams.IncludeDebugInformation = false; //添加相关的引用 //foreach (string assembly in assemblies) //{ // compilerParams.ReferencedAssemblies.Add(assembly); //} //compilerParams.ReferencedAssemblies.Add("mscorlib.dll"); //compilerParams.ReferencedAssemblies.Add("System.dll"); //if (this.CompilerVersion == "v3.5") //{ // compilerParams.ReferencedAssemblies.Add("System.Core.dll"); //} compilerParams.ReferencedAssemblies.Add("mscorlib.dll"); compilerParams.ReferencedAssemblies.Add("System.dll"); //compilerParams.ReferencedAssemblies.Add("System.Core.dll"); string path = ""; try { //System.Web.HttpContext.Current.Request.PhysicalApplicationPath + ("/Bin/WebSet.xml"); path = HttpContext.Current.Request.PhysicalApplicationPath +("/Bin/"); } catch { } compilerParams.ReferencedAssemblies.Add(path + "VSOnline.Framework.dll"); CSharpCodeProvider compiler = new CSharpCodeProvider(new Dictionary<string, string>() { { "CompilerVersion", CompilerVersion } }); //编译 code = code.Replace("Console.WriteLine", string.Format("VSOnline.Framework.Consoler.Outputs[/"{0}/"].WriteLine", id)); code = code.Replace("Console.Write", string.Format("VSOnline.Framework.Consoler.Outputs[/"{0}/"].Write", id)); CompilerResults results = compiler.CompileAssemblyFromSource(compilerParams, code); //错误 if (results.Errors.HasErrors) { foreach (CompilerError error in results.Errors) { Consoler.Outputs[id].Output.Add(error.ErrorText + "/n"); } return ReturnOutput(id); } //创建程序集 Assembly asm = results.CompiledAssembly; //获取编译后的类型 object mainClass = asm.CreateInstance("Program"); Type mainClassType = mainClass.GetType(); //输出结果 mainClassType.GetMethod("Main").Invoke(mainClass, null); return ReturnOutput(id); } private List<string> ReturnOutput(string id) { string[] output = new string[Consoler.Outputs[id].Output.Count]; Consoler.Outputs[id].Output.CopyTo(output, 0); Consoler.Outputs.Remove(id); return output.ToList(); } } }  

 

 

public class BLProgram { protected const string PROCESS_METHOD_CODE = @" using System; public class Program {{ public static void Main() {{ string parameter = ""{0}""; string result = ""{1}""; Detection(parameter,result); }} static void Detection(string testParameters,string testResults) {{ Console.WriteLine(testParameters+""-""+testResults); }} }}"; /// <summary> /// 判断程序题是否正确 /// </summary> /// <param name="strCode"></param> /// <returns></returns> public bool IsCProgramRight(string strCode) { string id = Guid.NewGuid().ToString(); List<string> output = new CodeRun().Run(strCode, id); string strOutpt = ""; for (int i = 0; i < output.Count; i++) { strOutpt += output[i]; } return (strOutpt == "对/n"); } /// <summary> /// 输出执行结果 /// </summary> /// <param name="strCode"></param> /// <returns></returns> public string GetOutPut(string strCode) { string id = Guid.NewGuid().ToString(); List<string> output = new CodeRun().Run(strCode, id); string strOutpt = ""; for (int i = 0; i < output.Count; i++) { strOutpt += output[i]; } return strOutpt; } /// <summary> /// 生成程序 /// </summary> /// <param name="parameter"></param> /// <param name="result"></param> /// <returns></returns> public string GetProgramStyle(string parameter, string result) { StringBuilder processMethod = new StringBuilder(); processMethod.AppendFormat(PROCESS_METHOD_CODE, parameter, result); return processMethod.ToString(); } /// <summary> /// 判断程序是否能生成成功 /// </summary> /// <param name="strCode"></param> /// <returns></returns> public bool BianYI(string strCode) { string id = Guid.NewGuid().ToString(); List<string> output = new CodeRun().Run(strCode, id); string strOutpt = ""; for (int i = 0; i < output.Count; i++) { strOutpt += output[i]; } return (strOutpt == "对/n" || strOutpt == "错/n"); } } 

你可能感兴趣的:(C# 动态编译代码实现)