c#动态编译与代码执行

1.来自链接 C#动态编译并执行代码 - 空明流光 - 博客园https://www.cnblogs.com/lyl6796910/p/4676842.htmlc#动态编译和执行代码_c#动态编译执行-CSDN博客,这里我代码整理了下.

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 System.CodeDom.Compiler;
using Microsoft.CSharp;
using System.Reflection;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Excute_code_1();
        }

        private void Excute_code_1()
        {
            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, textBox1.Text);

            if (cr.Errors.HasErrors)
            {
				//这里显示编译出错文字描述
                var msg = string.Join(Environment.NewLine, cr.Errors.Cast<CompilerError>().Select(err => err.ErrorText));
                MessageBox.Show(msg, "编译错误1");

				//这里显示编译出错代码
                var msg1 = string.Join(Environment.NewLine, cr.Errors.Cast<CompilerError>().Select(err => err.ErrorNumber));
                MessageBox.Show(msg1, "编译错误2");
                
				//这里显示编译出错行号
                var msg2 = string.Join(Environment.NewLine, cr.Errors.Cast<CompilerError>().Select(err => err.Line));
                MessageBox.Show(msg2, "编译错误3");
            }
            else
            {
                Assembly objAssembly = cr.CompiledAssembly;
                object objHelloWorld = objAssembly.CreateInstance("Test");
                if (objHelloWorld == null)
                {
                    Console.WriteLine("Instance Test is null!");
                    return;
                }
                
                MethodInfo objMI = objHelloWorld.GetType().GetMethod("method_1");
                if (objMI == null)
                {
                    Console.WriteLine("the method_1 method of Instance Test can not be invoked!");
                    return;
                }
                objMI.Invoke(objHelloWorld, null);                
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            init_code_1();
        }

        private void init_code_1()
        {
            textBox1.Clear();
            textBox1.AppendText("using System.Windows.Forms;\r\n");
            textBox1.AppendText("public class Test\r\n");
            textBox1.AppendText("{\r\n");
            textBox1.AppendText("   public void method_1()\r\n");
            textBox1.AppendText("   {\r\n");
            textBox1.AppendText("       MessageBox.Show(\"Hello world!\");\r\n");
            textBox1.AppendText("   }\r\n");
            textBox1.AppendText("}\r\n");
        }
    }
}

2.CompilerResults,CompilerErrorCollection类的说明可参考链接 https://www.cnblogs.com/swtool/p/7115065.html

namespace System.CodeDom.Compiler
{
    //
    // 摘要:
    //     表示从编译器返回的编译结果。
    public class CompilerResults
    {
        //
        // 摘要:
        //     初始化使用指定临时文件的 System.CodeDom.Compiler.CompilerResults 类的新实例。
        //
        // 参数:
        //   tempFiles:
        //     一个 System.CodeDom.Compiler.TempFileCollection,用它管理并存储对编译期间生成的中间文件的引用。
        public CompilerResults(TempFileCollection tempFiles);

        //
        // 摘要:
        //     获取或设置已编译的程序集。
        //
        // 返回结果:
        //     System.Reflection.Assembly,指示已编译的程序集。
        public Assembly CompiledAssembly { get; set; }
        //
        // 摘要:
        //     获取编译器错误和警告的集合。
        //
        // 返回结果:
        //     System.CodeDom.Compiler.CompilerErrorCollection,指示由编译产生的错误和警告(如果有)。
        public CompilerErrorCollection Errors { get; }
        //
        // 摘要:
        //     指示证据对象,该对象表示编译的程序集的安全策略权限。
        //
        // 返回结果:
        //     表示编译的程序集的安全策略权限的 System.Security.Policy.Evidence 对象。
        public Evidence Evidence { get; set; }
        //
        // 摘要:
        //     获取或设置编译器的返回值。
        //
        // 返回结果:
        //     编译器的返回值。
        public int NativeCompilerReturnValue { get; set; }
        //
        // 摘要:
        //     获取编译器输出消息。
        //
        // 返回结果:
        //     包含输出消息的 System.Collections.Specialized.StringCollection。
        public StringCollection Output { get; }
        //
        // 摘要:
        //     获取或设置已编译程序集的路径。
        //
        // 返回结果:
        //     程序集的路径;如果程序集是在内存中生成的,则为 null。
        public string PathToAssembly { get; set; }
        //
        // 摘要:
        //     获取或设置要使用的临时文件集合。
        //
        // 返回结果:
        //     一个 System.CodeDom.Compiler.TempFileCollection,用它管理并存储对编译期间生成的中间文件的引用。
        public TempFileCollection TempFiles { get; set; }
    }
}
namespace System.CodeDom.Compiler
{
    //
    // 摘要:
    //     表示 System.CodeDom.Compiler.CompilerError 对象的集合。
    [DefaultMember("Item")]
    public class CompilerErrorCollection : CollectionBase
    {
        //
        // 摘要:
        //     初始化 System.CodeDom.Compiler.CompilerErrorCollection 类的新实例。
        public CompilerErrorCollection();
        //
        // 摘要:
        //     初始化 System.CodeDom.Compiler.CompilerErrorCollection 类的新实例,该实例包含指定 System.CodeDom.Compiler.CompilerErrorCollection
        //     的内容。
        //
        // 参数:
        //   value:
        //     一个 System.CodeDom.Compiler.CompilerErrorCollection 对象,用来初始化集合。
        //
        // 异常:
        //   T:System.ArgumentNullException:
        //     value 为 <languageKeyword>null</languageKeyword>。
        public CompilerErrorCollection(CompilerErrorCollection value);
        //
        // 摘要:
        //     初始化包含指定的 System.CodeDom.Compiler.CompilerError 对象数组的 System.CodeDom.Compiler.CompilerErrorCollection
        //     新实例。
        //
        // 参数:
        //   value:
        //     用来初始化集合的 System.CodeDom.Compiler.CompilerError 对象数组。
        //
        // 异常:
        //   T:System.ArgumentNullException:
        //     value 为 null。
        public CompilerErrorCollection(CompilerError[] value);

        //
        // 摘要:
        //     获取或设置指定索引处的 System.CodeDom.Compiler.CompilerError。
        //
        // 参数:
        //   index:
        //     要在集合中定位的项的从零开始的索引。
        //
        // 返回结果:
        //     每个有效索引位置的 System.CodeDom.Compiler.CompilerError。
        //
        // 异常:
        //   T:System.ArgumentOutOfRangeException:
        //     index 参数指示的索引值不在集合的有效索引范围内。
        public CompilerError this[int index] { get; set; }

        //
        // 摘要:
        //     获取一个值,该值指示集合是否包含错误。
        //
        // 返回结果:
        //     如果集合包含错误,则为 true;否则为 false。
        public bool HasErrors { get; }
        //
        // 摘要:
        //     获取一个值,该值指示集合是否包含警告。
        //
        // 返回结果:
        //     如果集合包含警告,则为 true;否则为 false。
        public bool HasWarnings { get; }

        //
        // 摘要:
        //     将指定的 System.CodeDom.Compiler.CompilerError 对象添加到错误集合中。
        //
        // 参数:
        //   value:
        //     要添加的 System.CodeDom.Compiler.CompilerError 对象。
        //
        // 返回结果:
        //     新元素位置处插入的索引。
        public int Add(CompilerError value);
        //
        // 摘要:
        //     将数组元素复制到错误集合的末尾。
        //
        // 参数:
        //   value:
        //     System.CodeDom.Compiler.CompilerError 类型的数组,其中包含要添加到集合中的对象。
        //
        // 异常:
        //   T:System.ArgumentNullException:
        //     value 为 <languageKeyword>null</languageKeyword>。
        public void AddRange(CompilerError[] value);
        //
        // 摘要:
        //     将指定编译器的错误集合内容添加到错误集合的末尾。
        //
        // 参数:
        //   value:
        //     一个 System.CodeDom.Compiler.CompilerErrorCollection 对象,其中包含要添加到集合中的对象。
        //
        // 异常:
        //   T:System.ArgumentNullException:
        //     value 为 <languageKeyword>null</languageKeyword>。
        public void AddRange(CompilerErrorCollection value);
        //
        // 摘要:
        //     获取一个值,该值指示集合是否包含指定的 System.CodeDom.Compiler.CompilerError 对象。
        //
        // 参数:
        //   value:
        //     要定位的 System.CodeDom.Compiler.CompilerError。
        //
        // 返回结果:
        //     如果集合中包含 System.CodeDom.Compiler.CompilerError,则为 true;否则为 false。
        public bool Contains(CompilerError value);
        //
        // 摘要:
        //     将集合的值复制到一维 System.Array 实例的指定索引位置。
        //
        // 参数:
        //   array:
        //     一维 System.Array,是从 System.CodeDom.Compiler.CompilerErrorCollection 复制的值的目标。
        //
        //   index:
        //     数组中复制起始处的索引。
        //
        // 异常:
        //   T:System.ArgumentException:
        //     array 参数指示的数组是多维的。- 或 - System.CodeDom.Compiler.CompilerErrorCollection 中的元素数目大于
        //     array 参数指示的数组中的 arrayIndex 参数索引值和 array 参数指示的数组末尾之间的可用空间。
        //
        //   T:System.ArgumentNullException:
        //     array 参数为 null。
        //
        //   T:System.ArgumentOutOfRangeException:
        //     index 参数小于 array 参数指示的数组下限。
        public void CopyTo(CompilerError[] array, int index);
        //
        // 摘要:
        //     获取指定的 System.CodeDom.Compiler.CompilerError 对象在集合中的索引(如果它已存在于该集合中)。
        //
        // 参数:
        //   value:
        //     要定位的 System.CodeDom.Compiler.CompilerError。
        //
        // 返回结果:
        //     如果 System.CodeDom.Compiler.CompilerErrorCollection 中存在指定 System.CodeDom.Compiler.CompilerError
        //     的索引,则为该索引;否则为 -1。
        public int IndexOf(CompilerError value);
        //
        // 摘要:
        //     将指定的 System.CodeDom.Compiler.CompilerError 插入集合中的指定索引处。
        //
        // 参数:
        //   index:
        //     从零开始的索引,应在此处插入编译器错误。
        //
        //   value:
        //     要插入的 System.CodeDom.Compiler.CompilerError。
        public void Insert(int index, CompilerError value);
        //
        // 摘要:
        //     从集合中移除特定的 System.CodeDom.Compiler.CompilerError。
        //
        // 参数:
        //   value:
        //     要从 System.CodeDom.Compiler.CompilerErrorCollection 移除的 System.CodeDom.Compiler.CompilerError。
        //
        // 异常:
        //   T:System.ArgumentException:
        //     未在集合中找到指定的对象。
        public void Remove(CompilerError value);
    }
}
#region 程序集 System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
// C:\Windows\Microsoft.NET\Framework\v2.0.50727\System.dll
#endregion

namespace System.CodeDom.Compiler
{
    //
    // 摘要:
    //     表示编译器错误或警告。
    public class CompilerError
    {
        //
        // 摘要:
        //     初始化 System.CodeDom.Compiler.CompilerError 类的新实例。
        public CompilerError();
        //
        // 摘要:
        //     使用指定的文件名、行、列、错误号和错误文本初始化 System.CodeDom.Compiler.CompilerError 类的新实例。
        //
        // 参数:
        //   fileName:
        //     编译器遇到错误时正在编译的文件的文件名。
        //
        //   line:
        //     错误源所在的行。
        //
        //   column:
        //     错误源所在的列。
        //
        //   errorNumber:
        //     错误的错误号。
        //
        //   errorText:
        //     错误信息文本。
        public CompilerError(string fileName, int line, int column, string errorNumber, string errorText);

        //
        // 摘要:
        //     获取或设置错误源所在的列号。
        //
        // 返回结果:
        //     编译器遇到错误时所在的源文件列号。
        public int Column { get; set; }
        //
        // 摘要:
        //     获取或设置错误号。
        //
        // 返回结果:
        //     字符串形式的错误号。
        public string ErrorNumber { get; set; }
        //
        // 摘要:
        //     获取或设置错误信息的文本。
        //
        // 返回结果:
        //     错误信息的文本。
        public string ErrorText { get; set; }
        //
        // 摘要:
        //     获取或设置包含导致错误的代码的源文件的文件名。
        //
        // 返回结果:
        //     包含导致错误的代码的源文件的文件名。
        public string FileName { get; set; }
        //
        // 摘要:
        //     获取或设置一个值,该值指示错误是否是警告。
        //
        // 返回结果:
        //     如果错误是警告,则为 true;否则为 false。
        public bool IsWarning { get; set; }
        //
        // 摘要:
        //     获取或设置错误源所在的行号。
        //
        // 返回结果:
        //     编译器遇到错误时所在的源文件行号。
        public int Line { get; set; }

        //
        // 摘要:
        //     提供对象的 System.Object.ToString 方法的实现。
        //
        // 返回结果:
        //     编译器错误的字符串表示形式。
        public override string ToString();
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值