C#动态编译代码并执行

C#动态编译代码并执行

        private void Btn_Compile_Click(object sender, EventArgs e)
        {
            if (T_ClassName_Compile.Text.Length == 0 || T_Code.Text.Length == 0 || T_Function_Compile.Text.Length == 0)
            {
                MessageBox.Show("Pls enter function name and the C# code.");
                return;
            }

            CodeDomProvider cdp = CodeDomProvider.CreateProvider("C#");

            CompilerParameters cp = new CompilerParameters();
            cp.ReferencedAssemblies.Add("System.dll");
            cp.GenerateExecutable = false;
            cp.GenerateInMemory = true;

            CompilerResults cr = cdp.CompileAssemblyFromSource(cp, T_Code.Text);

            if (cr.Errors.HasErrors)
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendLine("Compile code error.");
                foreach (CompilerError error in cr.Errors)
                    sb.AppendLine(error.ErrorText);

                MessageBox.Show(sb.ToString());
                return;
            }

            Assembly ass = cr.CompiledAssembly;
            Type type = ass.GetType(T_ClassName_Compile.Text);
            MethodInfo mi = type.GetMethod(T_Function_Compile.Text);

            object[] objParams = null;
            if (T_Param_Compile.Text.Length != 0)
            {
                objParams = new object[1];
                objParams[0] = T_Param_Compile.Text;
            }

            T_Result_Compile.Text = (string)mi.Invoke(null, objParams);
        }


其中

  • T_ClassName_Compile.Text为代码中类的名字,如Compile.Compile
  • T_Function_Compile.Text为函数名称,如CompileFunc
  • T_Param_Compile.Text为参数
  • T_Code.Text为代码,例子中的代码如下:

    using System;
    namespace Compile
    {
    class Compile
    {
    public static string CompileFunc(string sMsg)
    {
        return "Compile function:" + sMsg;
    }
    }
    }


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值