使用 C# 动态编译代码和执行的代码
时间:2023-07-22 23:46:27
/*
* 使用 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();
}
标签:C#,动态编译
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
java使用Feign实现声明式Restful风格调用
2023-01-22 08:18:05
C#使用HttpClient的正确方式你了解吗
2023-07-04 12:12:40
![](https://img.aspxhome.com/file/2023/1/129721_0s.png)
Android监听电池状态实例代码
2022-01-31 21:28:32
深入学习C#网络编程之HTTP应用编程(上)
2023-12-12 23:12:27
![](https://img.aspxhome.com/file/2023/4/89834_0s.png)
一文看懂C#中List的扩容机制
2022-11-04 22:12:01
![](https://img.aspxhome.com/file/2023/3/129673_0s.png)
详解Java 中 RMI 的使用
2023-10-12 08:31:27
![](https://img.aspxhome.com/file/2023/5/98705_0s.jpg)
IDEA插件之彩虹括号Rainbow Brackets使用介绍
2022-03-14 09:09:51
![](https://img.aspxhome.com/file/2023/5/98125_0s.png)
使用Spring Data JDBC实现DDD聚合的示例代码
2022-05-04 05:11:23
Android 中 viewpager 滑动指示器的实例代码
2022-06-30 19:43:06
![](https://img.aspxhome.com/file/2023/2/119092_0s.jpg)
C#实现员工ID卡的识别功能
2021-08-11 23:49:25
![](https://img.aspxhome.com/file/2023/9/83349_0s.png)
Java毕业设计实战之平行志愿管理系统的实现
2023-09-12 14:34:23
![](https://img.aspxhome.com/file/2023/2/74872_0s.jpg)
Java内置GUI Frame类的使用
2021-10-25 18:06:49
![](https://img.aspxhome.com/file/2023/7/87187_0s.png)
Spring mvc拦截器实现原理解析
2023-06-06 15:26:33
Android实现简易秒表功能
2021-08-29 11:06:58
![](https://img.aspxhome.com/file/2023/6/95986_0s.jpg)
使用Sharding-JDBC对数据进行分片处理详解
2021-07-27 23:46:04
![](https://img.aspxhome.com/file/2023/2/108942_0s.jpg)
浅析Mybatis Plus和Mybatis的区别
2022-12-05 18:14:18
![](https://img.aspxhome.com/file/2023/8/85538_0s.jpg)
Java数据结构之并查集的实现
2023-06-29 06:58:32
android命令行模拟输入事件(文字、按键、触摸等)
2021-10-30 04:48:06
Java实体类不要使用基本类型的知识点总结
2023-02-21 10:04:49
C++与namespace有关的两个编译错误的讲解
2021-12-09 11:37:35