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. 开源项目托管到GitHub上

    前提是安装了git客户端 1.进入你的GitHub账户 2.点击new repositories   创建一个新的项目 输入项目名和项目描述   3.复制该项目的https路径 4.找一个文件夹来存放 ...

  2. 一文带你了解Java反射机制

    想要获取更多文章可以访问我的博客 - 代码无止境. 上周上班的时候解决一个需求,需要将一批数据导出到Excel.本来公司的中间件组已经封装好了使用POI生成Excel的工具方法,但是无奈产品的需求里面 ...

  3. SQL Server 插入数据时自增长列如何指定数值

    SQL Server 表在导入数据时,有时需要将自增长列指定数值,来保证导入前后的数据完全一致,如何实现? SQL Server 提供了方法: SET IDENTITY_INSERT,允许将显式值插入 ...

  4. 【Android】No resource found that matches the given name 'Theme.Sherlock.Light.NoActionBar'

    被这个问题困扰了好久…… 错误如下: error: Error retrieving parent for item: No resource found that matches the given ...

  5. 放出一批学生管理系统jsp源码,部分有框架

    基于jsp+struts 2的学生管理系统eclipse - 源码码头   https://www.icodedock.com/article/25.html 基于jsp+mysql的JSP学生成绩管 ...

  6. 手机APP测试之Fiddler

    之前测试基本上是web端,突然接手了一个要在指定pad上测试APP的任务,于是决定研究研究pad抓包.最开始考虑有jmeter进行抓包测试,发现抓不到(可能方法有问题,后续还需继续研究),然后用fid ...

  7. 1、大型项目的接口自动化实践记录--robotframework环境搭建

    因为人力.团队技术问题,选用robotframework来做自动化,首先说下环境搭建 齐涛道长的入门教程非常棒:http://blog.csdn.net/tulituqi/article/detail ...

  8. Unity经典游戏教程之:冒险岛

    版权声明: 本文原创发布于博客园"优梦创客"的博客空间(网址:http://www.cnblogs.com/raymondking123/)以及微信公众号"优梦创客&qu ...

  9. 7.19 包 logging模块 hashlib模块 openpyxl模块 深浅拷贝

    包 包是什么 他是一系列文件的结合体,表现形式就是文件夹 包的本质还是模块 他通常会有__init__.py文件 我们首先回顾一下模块导入的过程 import module首次导入模块(.py文件) ...

  10. html5标签整理

    html元素 基础标签 <!DOCTYPE> 定义文档类型(e.g  <!DOCTYPE  html>) <html>定义一个HTML文档</html> ...