动态执行C#代码示例
使用了静态类,所以在调用时不需要动态生成实例
主要使用
类库 Microsoft.CSharp里的CSharpCodeProvider类
类库System.CodeDom.Compiler里的CompilerParameters类
private void button1_Click(object sender, EventArgs e)
{
string s = "string s1=\"o\";string s2=\"k\";return s1+s2;";
Object ret = Execute(s);
MessageBox.Show(ret.ToString());
//Console.WriteLine(ret);
//Console.ReadKey();
}
static Object Execute(String code)
{
CSharpCodeProvider provider = new CSharpCodeProvider();
CompilerParameters parameters = new CompilerParameters();
CompilerResults results = provider.CompileAssemblyFromSource(parameters, BuildCode(code));
MethodInfo methodInfo = results.CompiledAssembly.GetType("C").GetMethod("T");
return methodInfo.Invoke(null, null);
}
static String BuildCode(String code)
{
StringBuilder builder = new StringBuilder();
builder.Append("using System;");
builder.Append("public class C{ public static Object T(){");
builder.Append(code);
builder.Append("}}");
return builder.ToString();
}