标签:反射 .com nbsp system gen inf 程序 trend ble
public class CodeProvider { //动态创建Driver类 private string strStart = "using System;" + "public static class Driver { public static void Main(){ "; private string strEnd = " } }"; /// <summary> /// 根据输入的文本动态编译,返回编译结果 /// </summary> public string CompileAndRun(string input, out bool IsError) { IsError = false; string returnData = ""; CompilerResults cr = null; using (var provider = new CSharpCodeProvider()) { var option = new CompilerParameters(); option.GenerateExecutable = true; var sb = new StringBuilder(); sb.Append(strStart); sb.Append(input); sb.Append(strEnd); //动态创建程序集 cr = provider.CompileAssemblyFromSource(option, sb.ToString()); } if (cr.Errors.HasErrors) { //如果编译遇到错误,输出错误信息 IsError = true; var errorInfo = new StringBuilder(); foreach (CompilerError item in cr.Errors) { errorInfo.AppendFormat("{0}:{1}\n", item.Line, item.ErrorText); } returnData = errorInfo.ToString(); } else { //把控制台重定向到TextWriter var writer = new StringWriter(); Console.SetOut(writer); //通过反射获取编译的程序集中Driver类 Type type = cr.CompiledAssembly.GetType("Driver"); //调用Main方法 type.InvokeMember("Main", BindingFlags.Public | BindingFlags.InvokeMethod | BindingFlags.Static, null, null, null); //获取函数在控制台输出的数据 returnData = writer.ToString(); } return returnData; } } CodeProvider cp = new CodeProvider(); bool isError; textBox6.Text = cp.CompileAndRun(textBox5.Text, out isError);
标签:反射 .com nbsp system gen inf 程序 trend ble
原文地址:http://www.cnblogs.com/chenjiachuan/p/7773138.html