当前位置: 移动技术网 > IT编程>开发语言>c# > 使用 C# 动态编译代码和执行的代码

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

2019年07月18日  | 移动技术网IT编程  | 我要评论
复制代码 代码如下:

/*
* 使用 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();
}

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网