1.代码视图:
2.RecordAttribute.cs
using System; namespace 自定义特性 { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = false)] public class RecordAttribute : Attribute { private readonly string _author; // 作者 private readonly DateTime _date; // 更新/创建 日期 private readonly string _recordType; // 记录类型:更新/创建 // 构造函数,构造函数的参数在特性中也称为“位置参数”。 //NOTE:注意构造函数的参数 date,必须为一个常量、Type类型、或者是常量数组,所以不能直接传递DateTime类型。 public RecordAttribute(string recordType, string author, string date) { _recordType = recordType; _author = author; _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; set; } } }
3.Program.cs
using System; using System.Reflection; namespace 自定义特性 { internal class Program { private static void Main(string[] args) { var demo = new DemoClass(); Console.WriteLine(demo.ToString()); MemberInfo reflection = typeof(DemoClass); var recordAttributes = Attribute.GetCustomAttributes(reflection, typeof(RecordAttribute)) as RecordAttribute[]; if (recordAttributes != null) { foreach (RecordAttribute attribute in recordAttributes) { if (attribute != null) { Console.WriteLine("时间:{0}", attribute.Date.ToString("yyyy-MM-dd HH:mm:ss")); Console.WriteLine("作者:{0}", attribute.Author); Console.WriteLine("备注:{0}", attribute.Memo); } } } Console.Read(); } } [Record("更新", "王五", "2012-12-24", Memo = "修改 ToString()方法")] [Record("更新", "李四", "2012-12-18", Memo = "修改文件")] [Record("创建", "张三", "2012-11-15", Memo = "创建文件")] public class DemoClass { public override string ToString() { return "This is a demo class"; } } }
4.运行结果: