WebEnh

.net7 mvc jquery bootstrap json 学习中 第一次学PHP,正在研究中。自学进行时... ... 我的博客 https://enhweb.github.io/ 不错的皮肤:darkgreentrip,iMetro_HD
  首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

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

Posted on 2024-05-27 21:52  WebEnh  阅读(229)  评论(0编辑  收藏  举报

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

界面有两个按钮,一个执行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);
      }
    }
  }
}

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

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

 

因为自定义代码中有

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