通过微软提供的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#中动态执行代码的更多相关文章

  1. 在VB中动态执行VBS代码,可操控窗体控件

    通过执行一段VBS代码来操控窗体内的控件也可以使用AddObject方法添加自己的类,那么在动态VBS代码中也一样可以使用在增加程序扩展性或是有脚本化需求的时候,这个方法还是不错的. Option E ...

  2. C#动态执行代码

          在开始之前,先熟悉几个类及部分属性.方法:CSharpCodeProvider.ICodeCompiler.CompilerParameters.CompilerResults.Assem ...

  3. SQLSERVER 在PROCEDURE 中动态执行SQL语句【EXEC】并获取

    1.直接上代码 CREATE PROCEDURE [dbo].[TEST] AS BEGIN DECLARE )='N8-4F', --構建SQL需要的條件 ),--構建後的SQL語句 @cnt in ...

  4. Oracle 函数中动态执行语句

    函数: 1 create or replace function fn_test(tablename in varchar2) return number is sqls ); rtn ):; beg ...

  5. Jmeter4.0---- jmeter中写入java代码_简单了解(15)

    1.说明 BeanShell:是一个小型嵌入式Java源代码解释器,具有对象脚本语言特性,能够动态地执行标准JAVA语法,并利用在JavaScript和Perl中常见的的松散类型.命令.闭包等通用脚本 ...

  6. 动态执行SQL语句,接收返回值

    一.exec和sp_executesql介绍 当需要根据外部输入的参数来决定要执行的SQL语句时,常常需要动态来构造SQL查询语句.比如,一个比较通用的分页存储过程,可能需要传入表名,字段,过滤条件, ...

  7. [Unity] 编辑器运行中动态编译执行C#代码

    (一)问题 之前写Lua时,修改完代码 reload 就可以热重载代码,调试起来十分方便(重构则十分痛苦). 现在使用 C# 做开发,目前还没找到比较方便地进行热重载的方式.只能退而求其次,在调试上找 ...

  8. 页面动态加入<script>标签并执行代码

    在页面中动态追加html片段的时候,有时候动态添加的代码会含有<script>标签,比如用了一些模板引擎,或者你的代码有些复杂的时候.然而我们用DOM提供的innerHTML方式来添加代码 ...

  9. C#动态执行字符串(动态创建代码)

    在编写C#程序的时候,有时我们需要动态生成一些代码并执行.然而C#不像JavaScript有一个Eval函数,可以动态的执行代码.所有这些功能都要我们自己去完成.如下是实例. 动态创建代码: usin ...

随机推荐

  1. Java 中的多线程你只要看这一篇就够了

    引 如果对什么是线程.什么是进程仍存有疑惑,请先Google之,因为这两个概念不在本文的范围之内. 用多线程只有一个目的,那就是更好的利用cpu的资源,因为所有的多线程代码都可以用单线程来实现.说这个 ...

  2. springboot 项目pom.xml文件基本配置

    <?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven ...

  3. NOIP 2016 换教室 (luogu 1850 & uoj 262) - 概率与期望 - 动态规划

    题目描述 对于刚上大学的牛牛来说,他面临的第一个问题是如何根据实际情况申请合适的课程. 在可以选择的课程中,有 2n2n 节课程安排在 nn 个时间段上.在第 ii(1 \leq i \leq n1≤ ...

  4. undefined reference to `vtable for MyColor'

    MyColor是新建的类,原因是使用了QObject,但是系统没有反应过来 解决:从工程删除,再添加进去[QtCreator]

  5. QML中打印

    1.console.log("123"); 2.console.log("a is ", a, "b is ", b); 3.打印代码块时间 ...

  6. String,InputStream相互转换

    一. InputStream转换为String 转换的过程是: 使用FileInputStream读取文件流: 使用InputStreamReader读取FileInputStream流: 使用Buf ...

  7. shell中使用echo输出时如何指定颜色

    答: 请看下图:

  8. bzoj4008: [HNOI2015]亚瑟王 dp

    题目链接 https://www.lydsy.com/JudgeOnline/problem.php?id=4008 思路 神仙啊 \(f[i][j]表示第i个点有j次机会(不管成功与否)\) \(f ...

  9. Maven集成Tomcat插件

    目录 类似插件及版本区别: 本地运行,启动嵌入式tomcat: 错误一: 错误二: Idea运行调试: vscode运行调试: 远程部署: 项目中的pom.xml配置: Tomcat中的tomcat- ...

  10. A^B mod C (快速幂+快速乘+取模)题解

    A^B mod C Given A,B,C, You should quickly calculate the result of A^B mod C. (1<=A,B,C<2^63). ...