标签:.net 标签 attributes
有时候,我们会看到这样的东西放在类或者方法上面:
[Obsolete("请更新方法")]
如下,定义了一个用于记录类变更的attribute,不允许继承,允许多次使用。
[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = true)] //
public class RecordAttribute:Attribute
{
private string recordType;//记录类型:更新/创建
private string author;//作者
private DateTime date;//创建/更新日期
private string memo;//备注
//构造函数,构造函数的参数在特性中也称为”位置参数“。
public RecordAttribute(string recordType, string author, string date) {
this.recordType = recordType;
this.author = author;
this.date = Convert.ToDateTime(date);
}
//对于位置参数,通常只提供get访问器
public string RecordType { get { return recordType; } }
public string Author { get { return author; } }
public DateTime Date { get { return date; } }
//构建一个属性,在特性中也叫”命名参数“
public string Memo {
get { return memo; }
set { memo = value; }
}
}
在类上使用的时候:
[Record("创建","lhc","2015年4月25日 15:38:24",Memo="这里是备注信息")]
[Record("修改", "lhc", "2015年4月25日 15:38:24", Memo = "这里是备注信息")]
public sealed class DemoClass : BaseClass, IDemoInterface, IdemoInterface2 {
private string name;
private string city;
public readonly string title;
public const string text = "const field";
public event DemoDelegate myEvent;
public string Name {
private get { return name; }
set { name = value; }
}
public DemoClass() {
title = "Readonly field";
}
public class NestedClass { }
public void SayGreeting(string name)
{
Console.WriteLine("morning:"+name);
}
}
不管是构造函数的参数还是属性,全部写到构造函数的圆括号中,对于构造函数的参数,必须采取构造函数参数的顺序和类型,因此叫做位置参数;对于属性,采用“属性=值”这样的格式,他们之间用逗号分隔,称作命名参数。
感觉对一个类的初始化信息都浓缩到了一行。。。压缩率蛮高的啊~
使用了attributes之后,我们就可以读取里面的信息了。基本思路跟获取类的元数据一样,先用取到type,然后,,嘿嘿,你懂得~要啥都有了。。。。
#region 利用反射查看自定义特性
Type t = typeof(Test.DemoClass);
Console.WriteLine("下面列出应用于{0}的RecordAttributes属性:" + t);
//获取所有的ReocordAttributes特性
object[] records = t.GetCustomAttributes(typeof(Test.RecordAttribute), false); //获取所有RecordAttribute标签
foreach (Test.RecordAttribute item in records)
{
Console.WriteLine("{0}", item.ToString());
Console.WriteLine("类型:{0}", item.RecordType);
Console.WriteLine("作者:{0}", item.Author);
Console.WriteLine("日期:{0}", item.Date.ToString());
if (!string.IsNullOrEmpty(item.Memo))
{
Console.WriteLine("备注:{0}",item.Memo);
}
}
#endregion
.Net:自定义特性(Custom Attributes)的创建与查看
标签:.net 标签 attributes
原文地址:http://blog.csdn.net/lhc1105/article/details/45251981