首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 自訂屬性實戰 (3):讀取屬性與反射應用

     編輯:關於C語言

簡單標記屬性:HideAttribute

class HideAttribute : System.Attribute
{
    // 僅需預設建構函式,不儲存資料
}

使用反射讀取屬性資料

讀取屬性需運用反射 API。以下範例掃描類別所有屬性,取得標記 AliasAttribute 的別名清單:

private Dictionary<string, string> GetAliasListing(Type destinationType)
{
    PropertyInfo[] destinationProperties = destinationType.GetProperties();
    var aliases = new Dictionary<string, string>();

    foreach (PropertyInfo property in destinationProperties)
    {
        object[] aliasAttributes = property.GetCustomAttributes(typeof(AliasAttribute), true);
        foreach (object attr in aliasAttributes)
        {
            foreach (string name in ((AliasAttribute)attr).Names)
                aliases.Add(name, property.Name);
        }
        aliases.Add(property.Name, property.Name); // 屬性名本身也作為別名
    }
    return aliases;
}

關鍵點

  • GetCustomAttributes 取得指定屬性陣列。
  • 遍歷屬性陣列,轉型為強型別屬性以存取資料。
  • 屬性名稱亦納入別名字典,利於序列化/反序列化對應。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved