C#在运行时动态创建类型的实现方法
作者:shichen2014 发布时间:2023-08-26 21:51:17
标签:C#,动态,创建,类型
本文实例讲述了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#警惕匿名方法造成的变量共享。分享给大家供大家参考,具体如下:匿名方法匿名方法是.NET 2.0中引入的高级特性,“匿名”二
- 排序二叉树概念二叉排序树(Binary Sort Tree),又称二叉查找树(Binary Search Tree),亦称二叉搜索树。是数据
- System.Threading.Timer 是由线程池调用的。所有的Timer对象只使用了一个线程来管理。这个线程知道下一个Timer对象
- 骑士周游问题在8x8的国际棋盘上,按照马走日的规则,验证是否能够走遍棋盘。解题思路1、创建棋盘 chessBoard,是一个二维数组。2、将
- Dubbo服务暴露机制前言在进行服务暴露机制的分析之前,必须谈谈什么是URL,在Dubbo服务暴露过程中URL是无处不在的,贯穿了整个过程。
- 前言枚举在java里也算个老生长谈的内容了,每当遇到一组需要类举的数据时我们都会自然而然地使用枚举类型:public enum Color
- 1.建议设置窗体为双缓冲绘图,可有效避免界面刷时引起的闪烁this.SetStyle(ControlStyles.AllPaintingIn
- public interface ICacheStrategy { &
- 本文实例为大家分享了Unity2D游戏回旋镖实现的具体代码,供大家参考,具体内容如下以下我举出2种同使用情况的回旋镖那么回旋镖需要怎么做呢?
- 1. 效果图展示2. 工程目录结构注意: webapp下的resources目录放置easyui和js(jQuery文件是另外的) 
- 一、前言现在在我们的项目中,使用多数据源已经是很常见的,下面,这里总结一下springboot整合jdbcTemplate配置多数据源的代码
- 为了让我提供的通用 Mapper 的 boot-starter 同时兼容 Spring Boot 1.x 和 2.x,增加了这么一个工具类。
- java联调生成测试数据工具类在日常的联调中,我们经常需要准备一定数量的测试数据,用来配合前端测试。当然对于简单的数据类型完全可以通过 JD
- 一:简介方法引用分为三种,方法引用通过一对双冒号:: 来表示,方法引用是一种函数式接口的另一种书写方式静态方法引用,通过类名::静态方法名,
- 本文实例为大家分享了Android SQLite数据库连接实现登录功能的具体代码,供大家参考,具体内容如下布局文件border.xml<
- 一直想练习下java多线程抓取数据。有天被我发现,铃声多多的官网(http://www.shoujiduoduo.com/main/)有大量
- 什么是适配器模式? 适配器模式(Adapter):将一个类的接口转换成客户希望的另外一个接口。Adapter模式使得原本由于接口不
- 现在语音识别已经被广泛的应用到各个领域中,在Unity开发中,语音识别也非常受欢迎。大部分人都会选择科大讯飞的语音识别功能,但是在一些小的项
- ForkJoin简介Fork/Join框架是Java 7提供的一种用于并行执行任务的框架,它将大任务分解为若干个小任务,并行执行这些小任务,
- SpringBoot自定义 * 和跨域配置冲突技术栈vue-cli3,springboot 2.3.2.RELEASE问题引出在做毕业设计过