asp.net 自定义特性
2024-10-11 21:33:45
今天看张子阳的.net中的反射(反射特性)一文,觉得反射配合自定义的特性确实还挺有用,之前看书、看博客之后好多心血来潮敲的代码随便往桌面上一放,时间一久,连自己也分不清它们是干嘛的了,然后就是删除,虽然写过不少,看的也够多,但什么也没留下,总感觉心里空荡荡的!所以,决定在这里记录下来练习代码。
先贴定义的特性类的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices; namespace AttributeTest
{
[Serializable]
[ComVisible(true)]
/*AttributeUsage顾名思义:这个特性用在什么地方,是用在类上呢,还是用在方法上,仰或是程序集上?
*能用在什么地方是其参数(AttributeTargets)决定滴(为什么?)。
* ArributeTargets是个枚举,正如下面一行代码所示,指定了RecordAttributes类(因为其继承了Attribute),做为特性用在Class和Method上。
* AllowMultiple参数呢?顾名思义是可以用于多行,不明白?好吧看看这个:
[Record("小小威", "修改了该类改动XXX", "2013-7-18 14:24:32")]
[Record("记忆中的马肠河", "修改了该类改动XXX", "2013-8-18 18:24:32")]
假如我们这个特性类创建好了,而且指定了AllowMultiple=true,就可以像这样(多行)用在类上或者方法上了。
*/
[AttributeUsage(AttributeTargets.Class|AttributeTargets.Method, AllowMultiple = true)]
//特性类要继承自Attribute类(为什么?),.net约定特性类要以Attribute做结尾
public class RecordAttribute : Attribute
{
//开发者
public string Name { get; set; }
//备注
public string Memo { get; set; }
//日期
public DateTime Date { get; set; }
//定义构造,RecordAttribute就是一个名符其实的类,因为其继承了Attribute,并且在其前面设定了特定,所以自己也就可以做为特性来用了。
public RecordAttribute(string name, string memo, string date)
{
this.Name = name;
this.Memo = memo;
this.Date =Convert.ToDateTime(date);
}
}
}
然后是如何用该特性:
#region 反射 特性
//用于测试自定义的特性(Attribute)类
AttributeTest att = new AttributeTest();
//type类是实现反射的关键
Type t = att.GetType();
//利用反射获取AttributeTest类的特性,并打印
object[] os = t.GetCustomAttributes(typeof(RecordAttribute), false);
Console.WriteLine("AttributeTest的特性信息:");
foreach (RecordAttribute item in os)
{
Console.WriteLine("操作员:" + item.Name + "," + "备注:" + item.Memo + "," + "日期:" + item.Date);
}
Console.WriteLine("AttributeTest的特性信息结束");
Console.WriteLine("AttributeTest的aa方法的特性信息:");
MethodInfo method = t.GetMethod("aa");
object[] mAtt = method.GetCustomAttributes(typeof(RecordAttribute), false);
foreach (RecordAttribute item in mAtt)
{
Console.WriteLine("操作员:" + item.Name + "," + "备注:" + item.Memo + "," + "日期:" + item.Date);
}
Console.WriteLine("AttributeTest的aa方法的特性结束");
#endregion
新建控制台程序,在program中引用AttributeTest,在main中拷贝该代码就可以直接运行。
用反射来获取类或者方法的特性的方式,能让我们更方便地获取代码的变更历史,相比较于用注释的方式,确实好多了。
最新文章
- 调用微信退款接口或发红包接口时出现System.Security.Cryptography.CryptographicException: 出现了内部错误 解决办法
- CocoaPods 安装 使用
- php5.3到php7.0.x新特性介绍
- Cocos2d 中的Sprite大小调整问题
- oracle utf8字符集转gbk(转)
- js将数组元素随机排序的方法
- PL/SQL 中文转换为\uxxxx格式(unicode)
- sql server 存储过程、事务,增删改
- CentOS 6.6下JDK1.7安装与配置(Linux)经典入门详解案例
- jQuery事件对象
- IIS充当代理转发请求到Kestrel
- H3C系列之三层交换机系统版本升级
- VS 2013Ultimate 开发过程中遇到的问题——listbox的隐藏问题,combobox.textchanged的中文问题
- vue 数据绑定实现的核心 Object.defineProperty()
- VC++ 实现INI文件读写操作
- A1pass大大对黑客学习的建议
- 如何将两个字段合成一个字段显示(oracle和sqlserver的区别)
- firefox打开链接自动跳转至新页面设置
- Centos6下编译安装gcc6.4.0
- 性能分析之– JAVA Thread Dump 分析