欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

使用 C# 动态编译代码和执行的代码

程序员文章站 2023-01-10 07:57:32
复制代码 代码如下: /* * 使用 c# 动态编译代码和执行 * 作者: yaob */ static void main(string[] args) { // 编译器...
复制代码 代码如下:

/*
* 使用 c# 动态编译代码和执行
* 作者: yaob
*/

static void main(string[] args)
{
// 编译器
codedomprovider cdp = codedomprovider.createprovider("c#");

// 编译器的参数
compilerparameters cp = new compilerparameters();
cp.referencedassemblies.add("system.dll");
cp.generateexecutable = false;
cp.generateinmemory = true;

// 编译结果
compilerresults cr = cdp.compileassemblyfromsource(cp, helloworld());

if (cr.errors.haserrors) console.writeline("编译出错!");
else
{
// 编译后的程序集
assembly ass = cr.compiledassembly;

// 得到helloworld类中的sayhello方法
type type = ass.gettype("helloworld.helloworld");
methodinfo mi = type.getmethod("sayhello");

// 执行
mi.invoke(null, null);
}
}

// 动态构建的代码
static string helloworld()
{
stringbuilder sbcode = new stringbuilder();
sbcode.appendline("using system;");
sbcode.appendline("namespace helloworld");
sbcode.appendline("{");
sbcode.appendline(" class helloworld");
sbcode.appendline(" {");
sbcode.appendline(" public static void sayhello()");
sbcode.appendline(" {");
sbcode.appendline(" console.writeline(\"hello~ world~!\");");
sbcode.appendline(" }");
sbcode.appendline(" }");
sbcode.appendline("}");
return sbcode.tostring();
}