Attribute 為程序元素(類、方法、組件等)附加聲明性元數據,編譯時嵌入元數據,運行時通過反射讀取。
[AttributeName(positionalParams, namedParam = value)] targetElement
| Attribute | 用途 | 關鍵參數 |
|---|---|---|
| AttributeUsage | 限制自定義 Attribute 適用目標 | validOn(AttributeTargets), AllowMultiple, Inherited |
| Conditional | 條件編譯方法調用 | conditionalSymbol (如 "DEBUG") |
| Obsolete | 標記過時成員,編譯警告/錯誤 | message, isError |
#define DEBUG
[Conditional("DEBUG")]
static void Log(string msg) => Console.WriteLine(msg);
// 僅 DEBUG 定義時調用生效,Release 版本調用點被移除
[Obsolete("Use NewMethod instead", true)] // true=編譯錯誤
static void OldMethod() {}
static void NewMethod() {}
System.Attribute 聲明類[MyAttr(...)]type.GetCustomAttributes()[AttributeUsage(Class|Constructor|Field|Method|Property, AllowMultiple=true)]
public class DeBugInfo : Attribute {
public int BugNo { get; }
public string Developer { get; }
public string LastReview { get; }
public string Message { get; set; }
public DeBugInfo(int no, string dev, string review) { ... }
}
[DeBugInfo(45, "Zara", "12/8/2012", Message="Mismatch")]
class Rectangle { ... }
下章將演示反射讀取此元數據。