C# 动态添加类、动态添加类型、代码添加类型

原文:C# 动态添加类、动态添加类型、代码添加类型

引用控件:

DLL下载地址:http://pan.baidu.com/s/1nv2GUWL

    public class TypeCreator
    {
        public static Type Creator(string ClassName, int PropertiesCount)
        {
            IDictionary<string, Type> Properties = new Dictionary<string, Type>();
            Type t = typeof(string);
            Properties.Add(new KeyValuePair<string, Type>("ID", typeof(int)));
            for (int i = 0; i < PropertiesCount; i++)
            {
                Properties.Add(new KeyValuePair<string, Type>("FF" + i, t));
            }
            return Creator(ClassName, Properties);
        }
        public static Type Creator(string ClassName, IDictionary<string, Type> Properties)
        {
            //应用程序域
            AppDomain currentDomain = System.Threading.Thread.GetDomain(); //AppDomain.CurrentDomain;
            //运行并创建类的新实例
            TypeBuilder typeBuilder = null;
            //定义和表示动态程序集的模块
            ModuleBuilder moduleBuilder = null;
            MethodBuilder methodBuilder = null;
            //表示类型属性
            PropertyBuilder propertyBuilder = null;
            //定义表示字段
            FieldBuilder fieldBuilder = null;
            //定义表示动态程序集
            AssemblyBuilder assemblyBuilder = null;
            //生成中间语言指令
            ILGenerator ilGenerator = null;
            //帮助生成自定义属性
            CustomAttributeBuilder cab = null;
            //指定方法属性的标志
            MethodAttributes methodAttrs;

            //Define a Dynamic Assembly
            //指定名称,访问模式
            assemblyBuilder = currentDomain.DefineDynamicAssembly(new AssemblyName("Test2"), AssemblyBuilderAccess.Run);

            //Define a Dynamic Module动态模块名称
            moduleBuilder = assemblyBuilder.DefineDynamicModule("ModuleName",true);

            //Define a runtime class with specified name and attributes.
            typeBuilder = moduleBuilder.DefineType(ClassName, TypeAttributes.Public | TypeAttributes.Class | TypeAttributes.BeforeFieldInit | TypeAttributes.Serializable);

            cab = new CustomAttributeBuilder(typeof(Castle.ActiveRecord.ActiveRecordAttribute).GetConstructor(Type.EmptyTypes), new object[0]);
            typeBuilder.SetCustomAttribute(cab);//

            cab = new CustomAttributeBuilder(typeof(Castle.ActiveRecord.PropertyAttribute).GetConstructor(Type.EmptyTypes), new object[0]);

            methodAttrs = MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig;
            foreach (KeyValuePair<string, Type> kv in Properties)
            {
                // Add the class variable, such as "m_strIPAddress"
                fieldBuilder = typeBuilder.DefineField("field_" + kv.Key, kv.Value, FieldAttributes.Public);

                propertyBuilder = typeBuilder.DefineProperty(kv.Key, System.Reflection.PropertyAttributes.HasDefault, kv.Value, null);
                if (kv.Key != "ID")
                {
                    propertyBuilder.SetCustomAttribute(cab);//
                }
                else
                {
                    propertyBuilder.SetCustomAttribute(new CustomAttributeBuilder(typeof(Castle.ActiveRecord.PrimaryKeyAttribute).GetConstructor(Type.EmptyTypes), new object[0]));//
                }

                methodBuilder = typeBuilder.DefineMethod("get_" + kv.Key, methodAttrs, kv.Value, Type.EmptyTypes);
                ilGenerator = methodBuilder.GetILGenerator();
                ilGenerator.Emit(OpCodes.Ldarg_0);
                ilGenerator.Emit(OpCodes.Ldfld, fieldBuilder);
                ilGenerator.Emit(OpCodes.Ret);
                propertyBuilder.SetGetMethod(methodBuilder);

                methodBuilder = typeBuilder.DefineMethod("set_" + kv.Key, methodAttrs, typeof(void), new Type[] { kv.Value });
                ilGenerator = methodBuilder.GetILGenerator();
                ilGenerator.Emit(OpCodes.Ldarg_0);
                ilGenerator.Emit(OpCodes.Ldarg_1);
                ilGenerator.Emit(OpCodes.Stfld, fieldBuilder);
                ilGenerator.Emit(OpCodes.Ret);
                propertyBuilder.SetSetMethod(methodBuilder);
            }
            //Create Class
            return typeBuilder.CreateType();
            return assemblyBuilder.GetType(ClassName);
            return moduleBuilder.GetType(ClassName);

        }
    }

原文地址:https://www.cnblogs.com/lonelyxmas/p/10612400.html

时间: 2024-07-29 18:59:37

C# 动态添加类、动态添加类型、代码添加类型的相关文章

JAVA“动态”为类添加属性

部分参考:http://www.cnblogs.com/zy2009/p/6725843.html pom.xml中添加: <dependency> <groupId>commons-beanutils</groupId> <artifactId>commons-beanutils</artifactId> <version>1.9.3</version> </dependency> <dependenc

为一个类动态的添加属性

/* 1不想集成一个类添加属性,想动态的添加一个属性 */ ||解决步骤 1.新建一个分类,导入 #import <objc/runtime.h> 2.添加属性(添加的属性,只是做了声明,并没有帮我们生成set,get方法) 3.手动添加set,get方法 {1.在set方法中实现 /* *@object 为那个对象添加属性 *@key  添加一个对应的key  c语言类型的 *@value  对应的值 *@objc_AssociationPolicy  策略 */ objc_setAssoc

给python类动态添加方法(method)

群里有人问如何做到 def foo(): pass class Bar(object): pass Bar.set_instance_method(foo) b = Bar() b.foo() 这个其实还是比较简单的, 只要写个函数给类设置属性即可, 可根据需求是否用函数包装下, 或者用staticmethod这个decorator: import functools def foo(): print 'hello world' class Bar(object): def __init__(s

动态的添加或者删除指定元素代码实例

动态的添加或者删除指定元素代码实例:本章节介绍一段代码实例,能够动态的添加或者删除指定的元素,这里不管实际应用中此代码出现的概率有多大,只在于如何实现类似的功能,代码实例如下: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="author" content="http://www.softwhy.com/" /&

ios runtime 动态向类添加方法

1.定义C函数: void dynamicMethodIMP(id self, SEL _cmd) { NSLog(@"蜗牛也疯狂"); } 2.重写函数+(BOOL)resolveInstanceMethod:(SEL)sel +(BOOL)resolveInstanceMethod:(SEL)sel { class_addMethod([self class], sel, (IMP)dynamicMethodIMP, "[email protected]:");

在python里如何动态添加类的动态属性呢?

body { font-family: "Microsoft YaHei UI","Microsoft YaHei",SimSun,"Segoe UI",Tahoma,Helvetica,Sans-Serif,"Microsoft YaHei", Georgia,Helvetica,Arial,sans-serif,宋体, PMingLiU,serif; font-size: 10.5pt; line-height: 1.5;

使用TypeDescriptor给类动态添加Attribute【转】

源文 : http://www.cnblogs.com/bicker/p/3326763.html 给类动态添加Attribute一直是我想要解决的问题,从msdn里找了很久,到Stack Overflow看了不少文章,算是最终有了答案. 先是有这样的一段解释 Attributes are static metadata. Assemblies, modules, types, members, parameters, and return values aren't first-class o

C/C++ (函数、变量和类)动态库的创建、导出和使用(图文+示例代码)

 一 Windows库 1引入库的原因: a.项目的复杂程度大 b.提高代码的利益利用率 2库的分类 2.1静态库: *.lib,不能被加载的程序,可以理解为目标程序的归档. 2.2动态库:*.dll,可以被应用程序加载的程序. 二 动态库 1动态库优点 1.1可以提供模块化的方式,方便协调开发(对于大项目,每个人写的东西编译为动态库,直接链接即可) 1.2对源代码保护 1.3减小可执行文件大小 1.4提高代码重用率 2动态库的基本使用方法 2.1动态库的创建 2.2加载动态库 2.3获取并

反射 学习笔记(二) 动态获取外部程序集中的类类型及成员类型

之前熟悉了反射相关的基本概念,知道了如何获取Assembly类和Type类,接下来通过一个小程序来练习.体验通过反射动态获取给定的*.dll或*.exe程序集所包含的所有类型的列表(列表包括给定类型定义的方法.字段.属性.事件.支持的接口.方法参数.基类.命名空间等).目标:使用Winform写一个小工具,可以查看指定dll的元数据. 界面如下: 使用的控件包括:按钮.OpenFileDialog对话框.ComboBox(DropDownList类型).TextBox(MultiLine为tru