您的位置:首页 > 编程语言

.NET中的代码动态编译执行

2010-07-12 16:47 381 查看
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
using System.CodeDom.Compiler;
using Microsoft.CSharp;

namespace WindowsFormsApplication5
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

//动态执行方法(c#版本):

public object EvalCSharp(string expression)
{
CodeDomProvider provider = new CSharpCodeProvider();
CompilerParameters cp = new CompilerParameters();
MethodInfo mi;

StringBuilder sb = new StringBuilder();
sb.AppendLine("using   System;");
sb.AppendLine("using   Microsoft.CSharp;");
sb.AppendLine("public   class   Mode");
sb.AppendLine("{");
sb.AppendLine("       public   static int   Func(){");
sb.AppendLine("                 return   " + expression + ";");
sb.AppendLine("       }");
sb.AppendLine("private static int GetData(){return 100;");
sb.AppendLine("       }");
sb.AppendLine("}");
cp.ReferencedAssemblies.Add("System.dll");
cp.GenerateExecutable = false;
cp.GenerateInMemory = true;

string code = sb.ToString();
CompilerResults cr = provider.CompileAssemblyFromSource(cp, code);

if (cr.Errors.HasErrors)
{
return null;
}
else
{
Assembly a = cr.CompiledAssembly;
Type t = a.GetType("Mode");
mi = t.GetMethod("Func", BindingFlags.Static | BindingFlags.Public);
return mi.Invoke(null, new object[0]);
}
}

private void button1_Click(object sender, EventArgs e)
{
//调用:
object csharp1 = EvalCSharp("GetData()");
object csharp2 = EvalCSharp("1 + 1 + 3");
this.Text = csharp1.ToString() ;
this.label1.Text = csharp2.ToString();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: