(转+整理)C#中动态执行代码

通过微软提供的CSharpCodeProvider,CompilerParameters,CompilerResults等类,可以在运行时,动态执行自己写的代码文件。原理就是把你的代码文件动态编译成exe或dll,或者在内存中输出,然后通过Assembly进行反射,执行其中的方法或访问其中的属性等。

(转+整理)C#中动态执行代码

界面有两个按钮,一个执行ShowMessage方法,另一个执行ShowForm方法,代码如下:

需引入

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.CSharp;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Reflection;

namespace CodeTest
{
  public partial class Test : Form
  {
    public Test()
    {
      InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
      CSharpCodeProvider objCSharpCodePrivoder = new CSharpCodeProvider();
      CompilerParameters objCompilerParameters = new CompilerParameters();

      objCompilerParameters.ReferencedAssemblies.Add("System.dll");
      objCompilerParameters.ReferencedAssemblies.Add("System.Windows.Forms.dll");

      objCompilerParameters.GenerateExecutable = false;
      objCompilerParameters.GenerateInMemory = true;

      CompilerResults cresult = objCSharpCodePrivoder.CompileAssemblyFromSource(objCompilerParameters, textBox1.Text);

      if (cresult.Errors.HasErrors)
      {
        foreach (CompilerError err in cresult.Errors)
        {
          MessageBox.Show(err.ErrorText);
        }
      }
      else
      {
        // 通过反射,执行代码
        Assembly objAssembly = cresult.CompiledAssembly;
        object obj = objAssembly.CreateInstance("CodeTest.Test");
        MethodInfo objMI = obj.GetType().GetMethod("ShowMessage");
        objMI.Invoke(obj, new object[] { "This is CodeTest!" });
      }
    }

    private void Form1_Load(object sender, EventArgs e)
    {
      textBox1.Text = "using System;" + Environment.NewLine +
             "using System.Windows.Forms;" + Environment.NewLine +
             Environment.NewLine +
             "namespace CodeTest" + Environment.NewLine +
             "{" + Environment.NewLine +
             " public partial class Test" + Environment.NewLine +
             " {" + Environment.NewLine +
             '\t' + "public void ShowMessage(string msg)" + Environment.NewLine +
             '\t' + "{" + Environment.NewLine +
             '\t' + " MessageBox.Show(msg);" + Environment.NewLine +
             '\t' + "}" + Environment.NewLine +
             Environment.NewLine +
             '\t' + "public void ShowForm()" + Environment.NewLine +
             '\t' + "{" + Environment.NewLine +
             '\t' + " Form frm = new Form();" + Environment.NewLine +
             '\t' + " frm.Show();" + Environment.NewLine +
             '\t' + "}" + Environment.NewLine +
             " }" + Environment.NewLine +
             "}";
    }

    private void button2_Click(object sender, EventArgs e)
    {

      CSharpCodeProvider objCSharpCodePrivoder = new CSharpCodeProvider();
      CompilerParameters objCompilerParameters = new CompilerParameters();

      objCompilerParameters.ReferencedAssemblies.Add("System.dll");
      objCompilerParameters.ReferencedAssemblies.Add("System.Windows.Forms.dll");

      objCompilerParameters.GenerateExecutable = false;
      objCompilerParameters.GenerateInMemory = true;

      CompilerResults cresult = objCSharpCodePrivoder.CompileAssemblyFromSource(objCompilerParameters, textBox1.Text);

      if (cresult.Errors.HasErrors)
      {
        foreach (CompilerError err in cresult.Errors)
        {
          MessageBox.Show(err.ErrorText);
        }
      }
      else
      {
        // 通过反射,执行代码
        Assembly objAssembly = cresult.CompiledAssembly;
        object obj = objAssembly.CreateInstance("CodeTest.Test");
        MethodInfo objMI = obj.GetType().GetMethod("ShowForm");
        objMI.Invoke(obj, null);
      }
    }
  }
}

点击按钮“执行代码”,运行结果如下:

(转+整理)C#中动态执行代码

点击按钮“显示窗体”,代码执行如下:

(转+整理)C#中动态执行代码

因为自定义代码中有

using System;
using System.Windows.Forms;

需要上面两个类库才能执行,所以要在CompilerParameters中对这两个dll添加引用,既

objCompilerParameters.ReferencedAssemblies.Add("System.dll");

objCompilerParameters.ReferencedAssemblies.Add("System.Windows.Forms.dll");

反射时,命名空间的名字要写完整,实例中命名空间是CodeTest,类是Test,所以反射代码是objAssembly.CreateInstance("CodeTest.Test")

文章转载自https://blog.csdn.net/bdmh/article/details/22398077

上一篇:linux arm irq (3): gpio interrupt


下一篇:阿里云一 第一篇:云服务器ECS