MSIL实用指南-给字段、属性、方法、类、程序集加Attribute
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的更多相关文章
- MSIL实用指南-创建字段
本篇讲解怎么创建字段,主要是在修饰符的创建上. 创建字段的方法是TypeBuilder.DefineField,传入字段名称.字段类型.字段修饰符等参数,返回一个FieldBuilder对象.先看这一 ...
- MSIL实用指南-生成索引器
MSIL实用指南-生成索引器 索引器是一种特殊的属性,它有参数的,也有get和set方法,属性名称一般是"Item",并且方法名称一般名称是"get_Item" ...
- c#基础3-方法的重载静态和非静态,字段属性,方法
方法的重载概念:方法的重载指的就是方法的名称相同给,但是参数不同.参数不同,分为两种情况1).如果参数的个数相同,那么参数的类型就不能相同.2).如果参数的类型相同,那么参数的个数就不能相同.***方 ...
- MSIL实用指南-Action的生成和调用
MSIL实用指南-Action的生成和调用 System.Action用于封装一个没有参数没有返回值的方法.这里生成需要Ldftn指令. 下面讲解怎生成如下的程序. class ActionTest ...
- C#-类 字段 属性 方法 特性
方法的签名 包括参数个数.参数类型.方法返回值 base和this关键字 1.使用base关键字,就可以使用父类中的字段.属性.方法 2.一旦父类中存在有参数的构造函数,那么子类就必须使用base来覆 ...
- MSIL实用指南-生成属性
本篇讲解怎么生成属性,包括get和set方法. 第一步,生成一个字段生成字段用TypeBuilder.DefineField方法.实例代码: FieldBuilder customerNameBldr ...
- MSIL实用指南-struct的生成和操作
struct(结构)是一种值类型,用于将一组相关的信息变量组织为一个单一的变量实体.所有的结构都继承自System.ValueType类,因此是一种值类型,也就是说,struct实例分配在线程的堆栈( ...
- MSIL实用指南-创建方法和定义参数
本篇讲解实现创建方法.指定参数的名称.实现参数加out和ref修饰符.以及参数加默认值. 创建方法 创建方法用类TypeAttributes的 DefineMethod(string name, Me ...
- MSIL实用指南-字段的加载和保存
字段有静态字段和非静态字段之分,它们的加载保存指令也是不一样的,并且非静态字段要生成this. 静态字段的加载加载静态字段的指令是Ldsfld.ilGenerator.Emit(OpCodes.Lds ...
随机推荐
- <<Modern CMake>> 翻译 1. CMake 介绍
<<Modern CMake>> 翻译 1. CMake 介绍 人们喜欢讨厌构建系统. 仅仅观看 CppCon17 上的演讲,就可以看到开发人员因为构建系统而闹笑话的例子. 这 ...
- webstorm mac 版破解
一.打开终端,输入: sudo vim /etc/hosts 回车后输入密码,编辑 hosts 文件,如图: 二.进入编辑模式(按 i 键),在最后一行添加如下代码: 0.0.0.0 account. ...
- 如何阅读zstack源码
个人的gitbook将会持续更新 https://www.gitbook.com/book/jingtyu/how-to-learn-zstack-code
- Helm 3 使用 harbor 作为仓库存储 charts
简介 本文讲述的是调教 Helm 3 和 harbor 1.6+ 的经验,从 helm2 更新到 helm 3 并且将 charts 推送到 harbor 中进行存储,移除了原先的 helm serv ...
- 287. 寻找重复数 Java解法
287. 寻找重复数 这题的难点就在于下面的说明了,我们先不管下面的那些说明的要求,用常规的解法来解答下上的题目. 排序思想解法 先把原来的数组进行排序,然后逐个遍历,一旦发现后一个元素和当前的元素相 ...
- 第二章 :初识MySQL
一.MySQL 1. MySQL的版本 社区版 企业帮 2.MySQL的优势 1.运行速度快 2.使用成本低 3.容易使用 4.可移植性高 5.适用更多用户 二.默认字符集设置 1.Standard ...
- On The Way—Step 2 Python入门之Python内容初始
2.1 输出 print() 打印一个字符串 print('你真好!') 打印变量内容 a = '你真好!' print(a) 结果都是:你真好! 2.2 变量 变量名字规则 只能用下划线.字 ...
- oracle查询截至到当前日期月份所在年份的所有月份
SELECT to_number(TO_CHAR(add_months(trunc(sysdate, 'yy'), ROWNUM - 1), 'MM')) as month FROM DUALCONN ...
- 精准营销、批量提取QQ群成员号码
有时我们在做精准营销时,需要从社群里提取群成员的QQ号,群发邮件,常规的做法是手工一个个复制粘贴,这样的效率无疑是很低的,下面我来分享一个批量获取社群的QQ号方法. 需要具备以下工具: 1.大量精准Q ...
- TensorFlow神经网络机器学习使用详细教程,此贴会更新!!!
运行 TensorFlow打开一个 python 终端: $ python >>> import tensorflow as tf >>> hello = tf.c ...