您的位置:首页 > 编程语言 > C#

C#动态加载创建程序集

2009-01-09 12:39 555 查看
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 ;

}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: