码迷,mamicode.com
首页 > Windows程序 > 详细

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

时间:2018-08-08 13:43:22      阅读:202      评论:0      收藏:0      [点我收藏+]

标签:message   代码执行   自己   enc   rpc   ESS   generic   objc   .dll   

通过微软提供的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

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

标签:message   代码执行   自己   enc   rpc   ESS   generic   objc   .dll   

原文地址:https://www.cnblogs.com/yeshenmeng/p/9441991.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!