C#动态编译代码到内存,并调用执行。
using System;
using System.Reflection;
using System.CodeDom.Compiler;
using Microsoft.CSharp;
public static void compiler()
{
string codeString = @"
public class CompilerTest
{
public static string GetTestString()
{
string MyStr = ""This is a Dynamic Compiler Demo!"";
return MyStr;
}
}";
CompilerParameters compilerParams = new CompilerParameters()
{
//编译器选项设置
CompilerOptions = "/target:library /optimize",
//编译时在内存输出
GenerateInMemory = true,
//生成调试信息
IncludeDebugInformation = false
};
//添加相关的引用
compilerParams.ReferencedAssemblies.Add("mscorlib.dll");
compilerParams.ReferencedAssemblies.Add("System.dll");
//ICodeCompiler compiler = new CSharpCodeProvider().CreateCompiler();
CSharpCodeProvider compiler = new CSharpCodeProvider(
new System.Collections.Generic.Dictionary<string, string>() { { "CompilerVersion", "v4.0" } }
);
//编译
CompilerResults results = compiler.CompileAssemblyFromSource(compilerParams, codeString);
//创建程序集
Assembly asm = results.CompiledAssembly;
//获取编译后的类型
object objMyTestClass = asm.CreateInstance("CompilerTest");
Type MyTestClassType = objMyTestClass.GetType();
//输出结果
Console.WriteLine(MyTestClassType.GetMethod("GetTestString").Invoke(objMyTestClass, null));
Console.ReadLine();
}
赞一个!!!!{:2_35:} 这个吊,支持! 真牛比,太吊了,支持
页:
[1]