using Microsoft.CSharp; |
using System; |
using System.CodeDom; |
using System.CodeDom.Compiler; |
using System.Collections.Generic; |
using System.Linq; |
using System.Reflection; |
using System.Text; |
using System.Threading.Tasks; |
namespace 测试程序 |
{ |
public class 通过 string 生成类 |
{ |
public Assembly CompileClass ( ) |
{ |
string code = @" |
|
public class Test |
{ |
public string name{get; set;} |
|
public int age{get; set;} |
}" ; |
CompilerResults compilerResults = CompileScript(code); //调用CompileScript 方法。 |
if (compilerResults.Errors.HasErrors) |
{ |
throw new InvalidOperationException( "Expression has a syntax error." ); |
} |
Assembly assembly = compilerResults.CompiledAssembly; //得到程序集对象。里面包含了类、接口、方法、属性。。。等等。 |
return assembly; |
} |
public CompilerResults CompileScript ( string source ) |
{ |
CompilerParameters parms = new CompilerParameters(); |
parms.GenerateExecutable = false ; // 是否生成exe 可执行文件。 |
parms.GenerateInMemory = true ; //是否在内存中生成space |
parms.IncludeDebugInformation = false ; //是否包含debug 信息 |
parms.ReferencedAssemblies.Add( "System.dll" ); |
parms.ReferencedAssemblies.Add( "Mongo.dll" ); |
|
CodeDomProvider compiler = CSharpCodeProvider.CreateProvider( "CSharp" ); |
return compiler.CompileAssemblyFromSource(parms, source); |
} |
} |
} |
by: 发表于:2017-12-27 10:09:16 顶(0) | 踩(0) 回复
??
回复评论