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.csdn.net/icedmilk/article/details/6724046

posted on 2013-02-27 16:04  《红猪》  阅读(599)  评论(0编辑  收藏  举报