C#编程中可以给字段、方法、类以及程序集加特性即继承于Attribute的类。这里讲解怎么在IL中给
它们加上特性。

生成字段的对应的类是FieldBuilder,生成属性的对应的类是PropertyBuilder,生成方法的对应的
类是MethodBuilder,生成类型的对应的类是TypeBuilder,生成程序集的对应的类是AssemblyBuilder。
这些类都有一个共同的方法SetCustomAttribute,而且参数都是一样的,具体是
SetCustomAttribute(CustomAttributeBuilder customBuilder)

我们可以用这个方法给它们添加特性。

步骤1:用反射获得特性的ConstructorInfo
比如

Type attrType = typeof(SerializableAttribute);
ConstructorInfo infoConstructor = attrType.GetConstructor(new Type[] { });

步骤2:创建一个CustomAttributeBuilder
CustomAttributeBuilder attributeBuilder = new CustomAttributeBuilder(infoConstructor,<infoConstructor参数数组>);

步骤3:调用SetCustomAttribute方法
上面说的FieldBuilder等等都是有同样的SetCustomAttribute方法,所以调用程序也是一样。

完成的程序如下

using System;
using System.Reflection;
using System.Reflection.Emit; namespace LX1_ILDemo
{
public class Demo20_CustomAttribute
{
static string binaryName = "Demo20_CustomAttribute.dll";
static string namespaceName = "LX1_ILDemo";
static string typeName = "CustomAttributeDemo"; static AssemblyBuilder assemblyBuilder;
static ModuleBuilder moduleBuilder;
static TypeBuilder typeBuilder; public static void Generate()
{
InitAssembly();
typeBuilder = moduleBuilder.DefineType(namespaceName + "." + typeName, TypeAttributes.Public | TypeAttributes.Abstract);
Generate_Field();
Generate_Property();
Generate_Method();
TypeAddAttr();
AssemblyAddAttr();
SaveAssembly();
Console.WriteLine("生成成功");
} static void TypeAddAttr()
{
Type attrType = typeof(SerializableAttribute);
ConstructorInfo infoConstructor = attrType.GetConstructor(new Type[] { });
CustomAttributeBuilder attributeBuilder = new CustomAttributeBuilder(infoConstructor, new object[] { });
typeBuilder.SetCustomAttribute(attributeBuilder);
} static void AssemblyAddAttr()
{
Type myType = typeof(AssemblyCopyrightAttribute);
ConstructorInfo infoConstructor = myType.GetConstructor(new Type[] { typeof(string) });
CustomAttributeBuilder attributeBuilder = new CustomAttributeBuilder(infoConstructor, new object[] { "IL Test Copyright" });
assemblyBuilder.SetCustomAttribute(attributeBuilder);
} static void Generate_Method()
{
Type attrType = typeof(System.ObsoleteAttribute);
ConstructorInfo infoConstructor = attrType.GetConstructor(new Type[] { });
CustomAttributeBuilder attributeBuilder = new CustomAttributeBuilder(infoConstructor, new object[] { }); MethodBuilder methodBuilder = typeBuilder.DefineMethod("Test",
MethodAttributes.Public | MethodAttributes.Abstract | MethodAttributes.Virtual,
typeof(void), new Type[] { }); methodBuilder.SetCustomAttribute(attributeBuilder);
} static void Generate_Field()
{
Type attrType = typeof(System.ObsoleteAttribute);
ConstructorInfo infoConstructor = attrType.GetConstructor(new Type[] { });
CustomAttributeBuilder attributeBuilder = new CustomAttributeBuilder(infoConstructor, new object[] { });
FieldBuilder fieldBuilder = typeBuilder.DefineField("Name", typeof(string), FieldAttributes.Private);
fieldBuilder.SetCustomAttribute(attributeBuilder);
} static void Generate_Property()
{
FieldBuilder fieldBuilder = typeBuilder.DefineField
("_Area", typeof(string), FieldAttributes.Private); PropertyBuilder propertyBuilder = typeBuilder.DefineProperty
("Area", PropertyAttributes.HasDefault, typeof(string), null); MethodAttributes getSetAttr =
MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig; MethodBuilder _methodBuilder =
typeBuilder.DefineMethod("get_Area", getSetAttr, typeof(string), Type.EmptyTypes); ILGenerator custNameGetIL = _methodBuilder.GetILGenerator(); custNameGetIL.Emit(OpCodes.Ldarg_0);
custNameGetIL.Emit(OpCodes.Ldfld, fieldBuilder);
custNameGetIL.Emit(OpCodes.Ret);
propertyBuilder.SetGetMethod(_methodBuilder); Type attrType = typeof(ObsoleteAttribute);
ConstructorInfo infoConstructor = attrType.GetConstructor(new Type[] { });
CustomAttributeBuilder attributeBuilder = new CustomAttributeBuilder(infoConstructor, new object[] { });
propertyBuilder.SetCustomAttribute(attributeBuilder);
} static void InitAssembly()
{
AssemblyName assemblyName = new AssemblyName(namespaceName);
assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndSave);
moduleBuilder = assemblyBuilder.DefineDynamicModule(assemblyName.Name, binaryName);
} static void SaveAssembly()
{
Type t = typeBuilder.CreateType(); //完成Type,这是必须的
assemblyBuilder.Save(binaryName);
}
}
}

MSIL实用指南-给字段、属性、方法、类、程序集加Attribute的更多相关文章

  1. MSIL实用指南-创建字段

    本篇讲解怎么创建字段,主要是在修饰符的创建上. 创建字段的方法是TypeBuilder.DefineField,传入字段名称.字段类型.字段修饰符等参数,返回一个FieldBuilder对象.先看这一 ...

  2. MSIL实用指南-生成索引器

    MSIL实用指南-生成索引器 索引器是一种特殊的属性,它有参数的,也有get和set方法,属性名称一般是"Item",并且方法名称一般名称是"get_Item" ...

  3. c#基础3-方法的重载静态和非静态,字段属性,方法

    方法的重载概念:方法的重载指的就是方法的名称相同给,但是参数不同.参数不同,分为两种情况1).如果参数的个数相同,那么参数的类型就不能相同.2).如果参数的类型相同,那么参数的个数就不能相同.***方 ...

  4. MSIL实用指南-Action的生成和调用

    MSIL实用指南-Action的生成和调用 System.Action用于封装一个没有参数没有返回值的方法.这里生成需要Ldftn指令. 下面讲解怎生成如下的程序. class ActionTest ...

  5. C#-类 字段 属性 方法 特性

    方法的签名 包括参数个数.参数类型.方法返回值 base和this关键字 1.使用base关键字,就可以使用父类中的字段.属性.方法 2.一旦父类中存在有参数的构造函数,那么子类就必须使用base来覆 ...

  6. MSIL实用指南-生成属性

    本篇讲解怎么生成属性,包括get和set方法. 第一步,生成一个字段生成字段用TypeBuilder.DefineField方法.实例代码: FieldBuilder customerNameBldr ...

  7. MSIL实用指南-struct的生成和操作

    struct(结构)是一种值类型,用于将一组相关的信息变量组织为一个单一的变量实体.所有的结构都继承自System.ValueType类,因此是一种值类型,也就是说,struct实例分配在线程的堆栈( ...

  8. MSIL实用指南-创建方法和定义参数

    本篇讲解实现创建方法.指定参数的名称.实现参数加out和ref修饰符.以及参数加默认值. 创建方法 创建方法用类TypeAttributes的 DefineMethod(string name, Me ...

  9. MSIL实用指南-字段的加载和保存

    字段有静态字段和非静态字段之分,它们的加载保存指令也是不一样的,并且非静态字段要生成this. 静态字段的加载加载静态字段的指令是Ldsfld.ilGenerator.Emit(OpCodes.Lds ...

随机推荐

  1. 技术派-不用sqrt手工计算平方根

    题目:任意长度数串,不使用sqrt函数,手工计算平方根?   要求只准用加/减/乘/除四则运算,不准使用power/sqrt等函数.   算法如下: 1.以小数点为中心往两边每2位分隔为一组: 2.然 ...

  2. markdown表情

    Emoji表情 将对应emoji表情的符号码复制后输入你的markdown文本即可显示emoji表情. 如:blush:,显示为

  3. 动态规划_Sumsets_POJ-2229

    Farmer John commanded his cows to search . Here are the possible sets of numbers that sum to : ) +++ ...

  4. 【iOS】stringWithFormat 保留小数点位数 float double

    以前就见过,如下: text = [NSString stringWithFormat:@"%.1f", percentageCompleted]; 但一直没在意.刚一时好奇,查了 ...

  5. SpringBoot RabbitMQ 整合使用

    ![](http://ww2.sinaimg.cn/large/006tNc79ly1g5jjb62t88j30u00gwdi2.jpg) ### 前提 上次写了篇文章,[<SpringBoot ...

  6. codeforces 327 B. Hungry Sequence

    题目链接 题目就是让你输出n个数的序列,要保证该序列是递增的,并且第i个数的前面不能保护它的约数,我直接先对前100000的素数打表,然后输出前n个,so easy. //cf 191 B #incl ...

  7. Linux 常用命令及使用方法

    1.  type   :查询命令 是否属于shell解释器 2.  help  : 帮助命令3.  man : 为所有用户提供在线帮助4.  ls  : 列表显示目录内的文件及目录 -l    以长格 ...

  8. 夯实Java基础(十三)——字符串

    字符串应该是我们在Java中用的最频繁.最多的,可见字符串对于我们来说是多么的重要,所以我们非常有必要去深入的了解一下. 1.String String就代表字符串,在Java中字符串属于对象.我们刚 ...

  9. Spring Cloud 之 Stream.

    一.简介 Spring Cloud Stream 是一个用来为微服务应用构建消息驱动能力的框架. Spring Cloud Stream 为一些供应商的消息中间件产品(目前集成了 RabbitMQ 和 ...

  10. Oracle GoldenGate mysql To Kafka上车记录

    一.前言 首先要学习一下ogg的所有进程,看着这张图来学习   Manager进程是GoldenGate的控制进程,运行在源端和目标端上.它主要作用有以下几个方面:启动.监控.重启Goldengate ...