C# 运行时编译代码并执行 【转】

本文介绍了一个使用C#进行动态编译及执行代码片段的例子。该示例展示了如何将一段字符串形式的C#代码编译成程序集,并通过反射调用其静态方法。此外还包含了错误处理流程,确保编译过程中的任何问题都能被捕捉并打印。
View Code
 1 public static void Main(string[] args)
 2         {
 3             string test = @"
 4             int MAX_N = 100;
 5             int n = 10;
 6             int i = 10;
 7             int k = 10;
 8             int l = 10;
 9             return ((n == MAX_N) && (i < MAX_N))|((k == MAX_N) && (l < MAX_N));
10             ";
11 
12             string code = CodeBegin + test + CodeEnd;
13             Console.WriteLine(code);
14             CSharpCodeProvider provider = new CSharpCodeProvider();
15             ICodeCompiler compiler = provider.CreateCompiler();
16             CompilerParameters param = new CompilerParameters();
17             param.ReferencedAssemblies.Add("System.dll");
18             param.GenerateExecutable = false;
19             param.GenerateInMemory = true;
20             CompilerResults cr = compiler.CompileAssemblyFromSource(param, code);
21             if (cr.Errors.HasErrors)
22             {
23                 Console.WriteLine("编译错误:");
24                 foreach (CompilerError err in cr.Errors)
25                     Console.WriteLine(err.ErrorText);
26             }
27             else
28             {
29                 Assembly assembly = cr.CompiledAssembly;
30                 MethodInfo mi = assembly.GetType("RuntimeCompute.JudgeCondition").GetMethod("GetValue");
31                 object value = mi.Invoke(null, null);
32                 Console.WriteLine(value);
33             }
34 
35             Console.ReadKey(true);
36         }
37         static string CodeBegin = @"
38 using System;
39 
40 namespace RuntimeCompute
41 {
42     class JudgeCondition
43     {
44         public static bool GetValue()
45         {
46 ";
47 
48         static string CodeEnd = @"
49         }
50     }
51 }
52 ";


 转自 http://blog.youkuaiyun.com/icedmilk/article/details/6724046

转载于:https://www.cnblogs.com/MasonRayn/archive/2013/02/27/2935330.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值