using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.CodeDom.Compiler ; using Microsoft.CSharp ; using System.Reflection ; using System.IO ; namespace WpfApplication2 { class CodeDriver { private string prefix = "using System;" + "public static class Driver" + "{" + "public static void Run()" + "{" ; private string postfix = "}" + "}" ; public string ComplieAndRun( string input , out bool hasError ) { hasError = false ; string returnData = null ; CompilerResults results = null ; using( CSharpCodeProvider provider = new CSharpCodeProvider() ) { CompilerParameters options = new CompilerParameters() ; options.GenerateInMemory = true ; StringBuilder sb = new StringBuilder() ; sb.Append( prefix ) ; sb.Append( input ) ; sb.Append( postfix ) ; results = provider.CompileAssemblyFromSource( options , sb.ToString() ) ; } //如果编译出错 if( results.Errors.HasErrors ) { hasError = true ; StringBuilder errorMsg = new StringBuilder() ; foreach( CompilerError e in results.Errors ) { errorMsg.AppendFormat( "{0} {1}" , e.Line , e.ErrorText ) ; } returnData = errorMsg.ToString() ; } else { TextWriter temp = Console.Out ; StringWriter writer = new StringWriter() ; Console.SetOut( writer ) ; Type type = results.CompiledAssembly.GetType( "Driver" ) ; type.InvokeMember( "Run" , BindingFlags.InvokeMethod | BindingFlags.Static | BindingFlags.Public , null , null ,null ) ; Console.SetOut( temp ) ; returnData = writer.ToString() ; } return returnData ; } } }