Attribute (特性) 是附加在程式碼元素 (類別、方法、屬性、參數、組件等) 上的宣告式中繼資料。編譯器將其編譯進組件中繼資料,執行期透過反射讀取,實現「自描述組件」。
| 特性 | 用途 | 範例 |
|---|---|---|
[Obsolete] | 標記過時成員 | [Obsolete("請用 NewMethod", true)] (true=編譯錯誤) |
[Serializable] | 標記可序列化 | [Serializable] public class Dto { } |
[AttributeUsage] | 限制自訂特性套用目標 | 見下文 |
[Conditional] | 條件編譯方法呼叫 | [Conditional("DEBUG")] |
[CallerMemberName] | 自動取得呼叫者名稱 | 參數預設值用於 Log/INotifyPropertyChanged |
using System;
public class HelpAttribute : Attribute
{
public HelpAttribute(string description)
{
Description = description;
}
public string Description { get; }
public string Url { get; set; } // 可選屬性 (named parameter)
}
Attribute 結尾
// 位置參數
[Help("這是一個範例類別")]
public class SampleClass { }
// 位置 + 命名參數
[Help("主要控制器", Url = "https://example.com/help")]
public class MainController { }
// 多個特性
[Serializable]
[Help("資料傳輸物件")]
public class UserDto { }
編譯器查找特性類別時,先找完整名稱,再嘗試加上 Attribute 後綴。
using System;
using System.Reflection;
var type = typeof(SampleClass);
var attrs = type.GetCustomAttributes(typeof(HelpAttribute), false);
foreach (HelpAttribute attr in attrs)
{
Console.WriteLine($"Description: {attr.Description}");
Console.WriteLine($"Url: {attr.Url ?? "N/A"}");
}
AttributeTargets 列舉定義:
Assembly, Module (需放在檔案最上方 [assembly: ...])Class, Struct, Enum, Interface, DelegateConstructor, Method, Property, Field, Event, Parameter, ReturnValue, TypeParameterAll = 以上全部下一篇將深入 [AttributeUsage] 控制特性套用規則:ValidOn (目標限制)、AllowMultiple (是否可重複)、Inherited (是否繼承)。