C# 在運行時動態建立類型

來源:互聯網
上載者:User

標籤:des   style   blog   color   os   io   ar   for   art   

C# 在運行時動態建立類型,這裡是通過動態產生C#原始碼,然後通過編譯器編譯成程式集的方式實現動態建立類型

public static Assembly NewAssembly()        {            //建立編譯器執行個體。               provider = new CSharpCodeProvider();            //設定編譯參數。               cp = new CompilerParameters();            cp.GenerateExecutable = false;            cp.GenerateInMemory = true;            // Generate an executable instead of             // a class library.            //cp.GenerateExecutable = true;            // Set the assembly file name to generate.            cp.OutputAssembly = "c:\\1.dll";            // Generate debug information.            cp.IncludeDebugInformation = true;            // Save the assembly as a physical file.            cp.GenerateInMemory = false;            // Set the level at which the compiler             // should start displaying warnings.            cp.WarningLevel = 3;            // Set whether to treat all warnings as errors.            cp.TreatWarningsAsErrors = false;            // Set compiler argument to optimize output.            cp.CompilerOptions = "/optimize";            cp.ReferencedAssemblies.Add("System.dll");            //cp.ReferencedAssemblies.Add("System.Core.dll");            cp.ReferencedAssemblies.Add("System.Data.dll");            //cp.ReferencedAssemblies.Add("System.Data.DataSetExtensions.dll");            cp.ReferencedAssemblies.Add("System.Deployment.dll");            cp.ReferencedAssemblies.Add("System.Design.dll");            cp.ReferencedAssemblies.Add("System.Drawing.dll");            cp.ReferencedAssemblies.Add("System.Windows.Forms.dll");            //建立動態代碼。                           StringBuilder classSource = new StringBuilder();            classSource.Append("using System;using System.Windows.Forms;\npublic   class   DynamicClass: UserControl \n");            classSource.Append("{\n");            classSource.Append("public DynamicClass()\n{\nInitializeComponent();\nConsole.WriteLine(\"hello\");}\n");            classSource.Append( "private System.ComponentModel.IContainer components = null;\nprotected override void Dispose(bool disposing)\n{\n");            classSource.Append( "if (disposing && (components != null)){components.Dispose();}base.Dispose(disposing);\n}\n");            classSource.Append( "private void InitializeComponent(){\nthis.SuspendLayout();this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);");            classSource.Append( "this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;this.Name = \"DynamicClass\";this.Size = new System.Drawing.Size(112, 74);this.ResumeLayout(false);\n}");            //建立屬性。               /*************************在這裡改成需要的屬性******************************/            classSource.Append(propertyString("aaa"));            classSource.Append(propertyString("bbb"));            classSource.Append(propertyString("ccc"));            classSource.Append("}");            System.Diagnostics.Debug.WriteLine(classSource.ToString());                      //編譯代碼。               CompilerResults result = provider.CompileAssemblyFromSource(cp, classSource.ToString());            if (result.Errors.Count > 0)            {                for( int i = 0; i < result.Errors.Count; i ++)                    Console.WriteLine(result.Errors[ i]);                Console.WriteLine("error");                return null;            }                        //擷取編譯後的程式集。               Assembly assembly = result.CompiledAssembly;            return assembly;        }        private static string propertyString(string propertyName)        {            StringBuilder sbProperty = new StringBuilder();            sbProperty.Append(" private   int   _" + propertyName + "   =   0;\n");            sbProperty.Append(" public   int   " + "" + propertyName + "\n");            sbProperty.Append(" {\n");            sbProperty.Append(" get{   return   _" + propertyName + ";}   \n");            sbProperty.Append(" set{   _" + propertyName + "   =   value;   }\n");            sbProperty.Append(" }");            return sbProperty.ToString();        }

C# 在運行時動態建立類型

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.