• C# 将字符串动态编译为Assembly


    /*
            using System.Reflection;
            using System.CodeDom;
            using System.CodeDom.Compiler;
             */
            private void Compiler()
            {
                CompilerParameters vCompilerParameters = new CompilerParameters();
                vCompilerParameters.GenerateExecutable = false;
                vCompilerParameters.GenerateInMemory = true;

                vCompilerParameters.ReferencedAssemblies.Add("System.Windows.Forms.dll");//添加引用
                string vSource =
                    "using System.Windows.Forms; " +//添加引用
                    "public class ClassTemp " +
                    "{ public ClassTemp(string ls_cs){MessageBox.Show(ls_cs);}" +
                    "    public void Test(string ls_test) " +
                    "    { " +
                    "         MessageBox.Show(ls_test);" +
                    "    } " +               
                    "} ";
                CompilerResults vCompilerResults =
                    CodeDomProvider.CreateProvider("CSharp").CompileAssemblyFromSource(vCompilerParameters, vSource);

                Assembly vAssembly = vCompilerResults.CompiledAssembly;//至此编译出Assembly

                Object[] args1 = new Object[1];
                args1[0] = "test";
                object vTemp = vAssembly.CreateInstance("ClassTemp", true, System.Reflection.BindingFlags.Default, null, args1, null, null);//创建类的实例
                MethodInfo vTest = vTemp.GetType().GetMethod("Test");//从实例中取到方法放入MethodInfo中         

                Object[] args = new Object[1];
                args[0] = "test";
                vTest.Invoke(vTemp, args);//调用方法
            }

  • 相关阅读:
    Nginx安装
    Nginx拦截指定国家的IP
    tomcat版本号隐藏或修改
    tomcat启动时卡住
    tomcat8 manager页面限制IP访问
    tomcat manager配置
    SpringBoot注解验证参数
    docker构建自定义镜像
    ubuntu安装docker以及基本用法
    使用idea创建一个maven工程
  • 原文地址:https://www.cnblogs.com/kuailewangzi1212/p/1358269.html
Copyright © 2020-2023  润新知