通過C#反射特性查看自定義特性
利用C#反射來查看自定義特性信息與查看其他信息類似,首先基于類型(本例中是DemoClass)獲取一個Type對象,然后調用Type對象的GetCustomAttributes()方法,獲取應用于該類型上的特性。當指定GetCustomAttributes(Type attributeType, bool inherit) 中的***個參數attributeType時,將只返回指定類型的特性,否則將返回全部特性;第二個參數指定是否搜索該成員的繼承鏈以查找這些屬性。
C#反射:代碼
- class Program {
- static void Main(string[] args) {
- Type t = typeof(DemoClass);
- Console.WriteLine("下面列出應用于 {0} 的RecordAttribute屬性:" , t);
- // 獲取所有的RecordAttributes特性
- object[] records = t.GetCustomAttributes(typeof(RecordAttribute), false);
- foreach (RecordAttribute record in records) {
- Console.WriteLine(" {0}", record);
- Console.WriteLine(" 類型:{0}", record.RecordType);
- Console.WriteLine(" 作者:{0}", record.Author);
- Console.WriteLine(" 日期:{0}", record.Date.ToShortDateString());
- if(!String.IsNullOrEmpty(record.Memo)){
- Console.WriteLine(" 備注:{0}",record.Memo);
- }
- }
- }
- }
輸出為:
下面列出應用于 AttributeDemo.DemoClass 的RecordAttribute屬性:
AttributeDemo.RecordAttribute
類型:更新
作者:Matthew
日期:2008-1-20
備注:修改 ToString()方法
AttributeDemo.RecordAttribute
類型:更新
作者:Jimmy
日期:2008-1-18
AttributeDemo.RecordAttribute
類型:創建
作者:張子陽
日期:2008-1-15
好了,到了這一步,我想將這些數據錄入數據庫中將不再是個問題,我們關于C#反射查看自定義特性的章節也就到此為止了。
【編輯推薦】