【C#】动态生成DLL

    public string Create_DLL(string classNamespace)
    {
        //string classNamespace/命名空间
        //string className 类名或表名
        String filenameDll= "";
        filenameDll= classNamespace + "DAL.dll";
        //生成一个可编译的单元,这是最根部的东西
        CodeCompileUnit compunit = new CodeCompileUnit();

        //  创建编译器实例//设置编译器对象
        CSharpCodeProvider csprovider = new CSharpCodeProvider();
        ICodeCompiler complier = csprovider.CreateCompiler();
      //  设置编译参数。 
        CompilerParameters paras = new CompilerParameters();
        paras.GenerateExecutable = false;   //编译成exe还是dll
        paras.GenerateInMemory = false;           //是否写入内存,不写入内存就写入磁盘
        paras.OutputAssembly = "d:\\" + filenameDll;         //输出路径
        paras.IncludeDebugInformation = false; //是否产生pdb调试文件      默认是false

        paras.ReferencedAssemblies.Add("System.dll");//添加引用DLL
        paras.ReferencedAssemblies.Add("System.Data.dll");//添加引用DLL
          
        StringBuilder classSource = new StringBuilder();
        classSource.Append("using System;\r\n");
        classSource.Append("using System.Collections.Generic;\r\n");
        classSource.Append("using System.Text;\r\n");
        classSource.Append("using System.Data;\r\n");//#region 命名空间及类名
        classSource.Append("namespace " + classNamespace + ".DAL \r\n");
        classSource.Append("{ \r\n");
       {
            //定义类开始
            classSource.Append("    public class " + classNamespace + "_DAL\r\n");
            classSource.Append("    {  \r\n");

                //定义字段
            classSource.Append("       public  string Name { get; set; } \r\n");
                //定义字段结束
                //定义方法
      classSource.Append("public string GetName(){return \"关注微信公众号:维基动漫\";} \r\n");
          //定义方法结束 classSource.Append(
" } \r\n"); //类定义结束 } classSource.Append("} \r\n"); //命名空间定义结束 // System.Diagnostics.Debug.WriteLine(classSource.ToString()); // 调试用。注释掉 // 编译代码。 CompilerResults result = complier.CompileAssemblyFromSource(paras, classSource.ToString()); // 获取编译后的程序集。 //Assembly assembly = result.CompiledAssembly; return classSource.ToString(); //// 动态调用方法。 //object eval = assembly.CreateInstance(className); //MethodInfo method = eval.GetType().GetMethod(methodName); // object reobj = "生成dll成功";// method.Invoke(eval, null); //GC.Collect(); // return reobj; }

 

参考原文:https://www.cnblogs.com/greefsong/archive/2012/07/19/2599186.html

 

posted on 2023-02-09 14:01  梦琪小生  阅读(192)  评论(0编辑  收藏  举报

导航