在netfarmerwork3.5版本的winform下执行string串中的代码

时间:2021-06-04 19:41:14   收藏:0   阅读:0
namespace TestQuestionaire
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void bt_ok_Click(object sender, EventArgs e)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("using System;");
            sb.Append("using System.Text;");
            //sb.Append("using Model;");
            sb.Append("namespace DynamicCodeGenerate");
            sb.Append("{");
            sb.Append(" public class HelloWorld ");
            sb.Append("{");
            sb.Append(" public string OutPut(string value) ");
            sb.Append("{");
            sb.Append(" return \"Hello World!\"+value; ");
            sb.Append("}");
            sb.Append("}}");
            string code = sb.ToString();

            CodeDomProvider provider = CodeDomProvider.CreateProvider("C#");
            CSharpCodeProvider objCSharpCodePrivoder = new CSharpCodeProvider();
            //添加程序集
            CompilerParameters objCompilerParameters = new CompilerParameters();
            objCompilerParameters.ReferencedAssemblies.Add("System.dll");
            /*
             * 第一 要引用要在当前项目中引用Model
             * 第二 在拼接代码的时候也要引用命名空间 using Model;
             */
            //objCompilerParameters.ReferencedAssemblies.Add("Model.dll");
            objCompilerParameters.GenerateExecutable = false;//不生成可执行文件
            objCompilerParameters.GenerateInMemory = true;//在内存中输出
            CompilerResults cr;
            //已过时
            // ICodeCompiler objICodeCompiler = objCSharpCodePrivoder.CreateCompiler();
            // cr= objICodeCompiler.CompileAssemblyFromSource(objCompilerParameters, GenerateCode());
            cr = provider.CompileAssemblyFromSource(objCompilerParameters, code);
            if (cr.Errors.HasErrors)
            {
                //Console.WriteLine("编译错误!");
                foreach (CompilerError err in cr.Errors)
                {
                    //Console.WriteLine(err.ErrorText);
                }
            }
            else
            {
                //通过反射,调用hello world 的实例
                Assembly objAssembly = cr.CompiledAssembly;
                Object objHelloWorld = objAssembly.CreateInstance("DynamicCodeGenerate.HelloWorld");
                MethodInfo objMI = objHelloWorld.GetType().GetMethod("OutPut");
                var result = objMI.Invoke(objHelloWorld, new object[] { "jcdd" });
                this.rtb_content.Text = result.ToString();
            }
        }
    }
}

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!