C#在运行时动态创建类型的实现方法

作者:shichen2014 时间:2023-08-26 21:51:17 

本文实例讲述了C#在运行时动态创建类型的实现方法。是C#项目开发中很实用的技巧。分享给大家供大家参考。具体分析如下:

具体来说,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#程序设计有所帮助

标签:C#,动态,创建,类型
0
投稿

猜你喜欢

  • Android Camera+SurfaceView自动聚焦防止变形拉伸

    2023-06-18 06:35:54
  • java启动线程的3种方式对比分析

    2023-12-17 08:38:41
  • 浅谈java多线程wait,notify

    2023-11-29 16:29:03
  • 深入理解以DEBUG方式线程的底层运行原理

    2022-07-12 03:19:40
  • Unity3D实现飞机大战游戏(2)

    2021-11-16 10:41:38
  • eclipse如何搭建Springboot项目详解

    2023-11-29 04:52:36
  • C#使用System.Net邮件发送功能踩过的坑

    2022-09-09 18:16:11
  • Android开发使用Handler的PostDelayed方法实现图片轮播功能

    2023-10-20 04:37:42
  • C#中的不可变数据类型介绍(不可变对象、不可变集合)

    2022-06-13 19:08:33
  • redisson实现分布式锁原理

    2023-11-29 00:00:00
  • 基于SpringMVC的全局异常处理器介绍

    2023-11-23 20:55:58
  • Java进阶知识之反射的概念与获取方法

    2023-12-09 19:09:14
  • Mybatis常用分页插件实现快速分页处理技巧

    2022-12-25 00:03:45
  • 解决IDEA service层跳转实现类的快捷图标消失问题

    2022-09-03 06:38:00
  • Spring Boot整合mybatis使用注解实现动态Sql、参数传递等常用操作(实现方法)

    2023-03-17 07:09:32
  • Android rom解包打包工具

    2023-09-01 21:49:10
  • Java实现的双向匹配分词算法示例

    2023-06-23 08:29:32
  • 详解Java策略模式

    2022-03-20 12:17:05
  • Java 二分查找算法的实现

    2022-07-23 11:10:13
  • C#如何优雅的结束线程

    2022-07-27 19:45:27
  • asp之家 软件编程 m.aspxhome.com