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 取得指定屬性陣列。