zoukankan      html  css  js  c++  java
  • (转+整理)C#中动态执行代码

    通过微软提供的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 +
                 ' ' + "public void ShowMessage(string msg)" + Environment.NewLine +
                 ' ' + "{" + Environment.NewLine +
                 ' ' + " MessageBox.Show(msg);" + Environment.NewLine +
                 ' ' + "}" + Environment.NewLine +
                 Environment.NewLine +
                 ' ' + "public void ShowForm()" + Environment.NewLine +
                 ' ' + "{" + Environment.NewLine +
                 ' ' + " Form frm = new Form();" + Environment.NewLine +
                 ' ' + " frm.Show();" + Environment.NewLine +
                 ' ' + "}" + 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

  • 相关阅读:
    PHP的五大运行模式
    PHP设计模式-工厂模式
    php+redis实现消息队列
    面试题一
    Linux常用命令
    实现session在多台服务器上共享
    Memcache和redis的区别
    PHP设计模式-建造者模式
    FASTCgi和PHP-fpm关系
    安装vm虚拟机
  • 原文地址:https://www.cnblogs.com/yeshenmeng/p/9441991.html
Copyright © 2011-2022 走看看