屬性是編譯時期附加在型別、成員、參數等程式元素上的中繼資料。.NET 執行階段可透過反射讀取這些資訊,進而改變程式行為或提供額外功能。常見內建屬性如 [Obsolete]、[Serializable]、[WebMethod] 等。
[Hide])還是攜帶參數(如 [Alias("Name", "First")])?繼承 System.Attribute,慣例命名以 Attribute 結尾:
[AttributeUsage(AttributeTargets.Property, AllowMultiple = true)]
public class AliasAttribute : Attribute {
public string[] Names { get; }
public AliasAttribute(params string[] names) => Names = names;
}
public class HideAttribute : Attribute { } // 純標記,無建構函數參數
public class User {
[Hide]
public string SSN { get; set; }
[Alias("FirstName", "First")]
public string FName { get; set; }
}
public static Dictionary<string, string> GetAliasMap(Type type) {
var map = new Dictionary<string, string>();
foreach (var prop in type.GetProperties()) {
var attrs = prop.GetCustomAttributes<AliasAttribute>(inherit: true);
foreach (var attr in attrs) {
foreach (var name in attr.Names)
map[name] = prop.Name;
}
map[prop.Name] = prop.Name; // 原名也映射
}
return map;
}
關鍵 API:MemberInfo.GetCustomAttributes<T>()、Attribute.GetCustomAttribute()。
ConcurrentDictionary)GetCustomAttributesSystem.ComponentModel.DataAnnotations 內建驗證屬性減少自訂需求