C#动态编译代码并执行

来源:互联网 发布:阿提拉全面战争 知乎 编辑:程序博客网 时间:2024/04/28 22:19

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