zoukankan      html  css  js  c++  java
  • C#动态编译并执行代码

    先来张运行时截图:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using Microsoft.CSharp;
    using System.CodeDom.Compiler;
    using System.Reflection;
    
    namespace CSharpDynamicCode
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            private void btnRun_Click(object sender, EventArgs e)
            {
                run();
            }
    
            void run()
            {
                CSharpCodeProvider objCSharpCodePrivoder = new CSharpCodeProvider();
                ICodeCompiler objICodeCompiler = objCSharpCodePrivoder.CreateCompiler();
    
                CompilerParameters objCompilerParameters = new CompilerParameters();
    
                //添加需要引用的dll
                objCompilerParameters.ReferencedAssemblies.Add("System.dll");
                objCompilerParameters.ReferencedAssemblies.Add("System.Windows.Forms.dll");
    
                //是否生成可执行文件
                objCompilerParameters.GenerateExecutable = false;
    
                //是否生成在内存中
                objCompilerParameters.GenerateInMemory = true;
    
                //编译代码
                CompilerResults cr = objICodeCompiler.CompileAssemblyFromSource(objCompilerParameters, txtCode.Text);
    
                if (cr.Errors.HasErrors)
                {
                    var msg = string.Join(Environment.NewLine, cr.Errors.Cast<CompilerError>().Select(err => err.ErrorText));
                    MessageBox.Show(msg, "编译错误");
                }
                else
                {
                    Assembly objAssembly = cr.CompiledAssembly;
                    object objHelloWorld = objAssembly.CreateInstance("Test");
                    MethodInfo objMI = objHelloWorld.GetType().GetMethod("Hello");
                    objMI.Invoke(objHelloWorld, null);
                }
            }
    
            private void Form1_Load(object sender, EventArgs e)
            {
    
            }
        }
    }
  • 相关阅读:
    bzoj 1017 魔兽地图DotR
    poj 1322 chocolate
    bzoj 1045 糖果传递
    poj 3067 japan
    timus 1109 Conference(二分图匹配)
    URAL 1205 By the Underground or by Foot?(SPFA)
    URAL 1242 Werewolf(DFS)
    timus 1033 Labyrinth(BFS)
    URAL 1208 Legendary Teams Contest(DFS)
    URAL 1930 Ivan's Car(BFS)
  • 原文地址:https://www.cnblogs.com/nanfei/p/6046128.html
Copyright © 2011-2022 走看看