433
技術社區[雲棲]
C# 自定義特性
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.運行結果:
最後更新:2017-04-04 07:03:12