C# 特性 (Attribute) 允許在編譯時將元數據附加到程序元素 (類、方法、屬性、參數、程序集等),運行時通過反射讀取,驅動框架行為(序列化、驗證、路由、依賴注入、AOP、代碼生成)。本文系統講解預定義特性、自定義特性開發、AttributeUsage 控制、繼承規則、反射檢索模式與實戰反模式。
| 特性 | 命名空間 | 作用 | 典型場景 |
|---|---|---|---|
[Obsolete] | System | 標記過時成員,編譯警告/錯誤 | API 版本演進 |
[Conditional] | System.Diagnostics | 條件編譯調用 | Debug.Log、Trace、契約檢查 |
[Serializable] | System | 標記類型可序列化 | BinaryFormatter、Remoting (舊) |
[AttributeUsage] | System | 控制自定義特性使用規則 | 元特性,必學 |
[CallerMemberName] / CallerFilePath / CallerLineNumber | System.Runtime.CompilerServices | 編譯器自動填充調用者信息 | INotifyPropertyChanged、日誌、源碼生成器 |
[DoesNotReturn] / [DoesNotReturnIf] | System.Diagnostics.CodeAnalysis | 靜態分析輔助 (C# 10+) | ThrowHelper、契約驗證 |
[RequiredMember] | System.Runtime.CompilerServices | 強制對象初始化器設置 (C# 11+) | 不可變對象構建 |
// 1. 繼承 System.Attribute
// 2. 慣例命名以 Attribute 結尾
// 3. 僅包含構造函數參數、只讀屬性/字段 (不可變性)
using System;
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class HelpAttribute : Attribute
{
public HelpAttribute(string description)
{
Description = description;
}
public string Description { get; } // 唯讀屬性
public string Url { get; set; } // 可選命名參數
}
[Help("核心業務實體", Url = "https://wiki.example.com/entity")]
public class Order { }
[Help("計算訂單總價")]
public decimal CalculateTotal() => Items.Sum(i => i.Price * i.Quantity);
| 屬性 | 類型 | 默認值 | 說明 |
|---|---|---|---|
| ValidOn | AttributeTargets (Flags 枚舉) | All | 允許標注的程序元素:Class, Struct, Method, Property, Field, Parameter, Assembly, Module, Enum, Interface, Delegate, ReturnValue, GenericParameter 等 |
| AllowMultiple | bool | false | true 允許同一元素多次應用同一特性 |
| Inherited | bool | true | true 允許派生類繼承基類特性 (僅類/接口繼承有效,成員重寫不繼承) |
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = true, Inherited = false)]
public class PluginAttribute : Attribute { }
[Help("Base")]
public class Base { }
[Help("Derived")]
public class Derived : Base { }
// 查詢 Derived 的 HelpAttribute
var attrs = typeof(Derived).GetCustomAttributes(inherit: true);
// inherit=true (默認) 且 HelpAttribute.Inherited=true → 返回 [Base, Derived] (AllowMultiple=true)
// inherit=true 且 HelpAttribute.Inherited=false → 僅返回 [Derived]
// inherit=false → 僅返回 [Derived] (不查找基類)
關鍵點:Inherited 僅影響**類/接口繼承鏈**的查找,**不影響**方法重寫、接口實現、屬性覆蓋等成員級繼承(成員級需手動遍歷)。
var attrs = typeof(T).GetCustomAttributes(inherit: true);
var attr = typeof(T).GetCustomAttribute(inherit: true); // 單個
bool has = typeof(T).IsDefined(typeof(TAttribute), inherit: true);
// 方法
var method = typeof(T).GetMethod("MethodName");
var attrs = method.GetCustomAttributes(inherit: true);
// 參數
var param = method.GetParameters()[0];
var attrs = param.GetCustomAttributes(inherit: false);
// 返回值
var retAttr = method.ReturnParameter.GetCustomAttributes(false);
// 程序集級
var asmAttrs = Assembly.GetExecutingAssembly().GetCustomAttributes();
public static class AttributeCache where TAttribute : Attribute
{
private static readonly ConcurrentDictionary Cache = new();
public static TAttribute[] Get(MemberInfo member, bool inherit = true)
=> Cache.GetOrAdd(member, m => m.GetCustomAttributes(inherit).ToArray());
}
[ConfigSection("Database")]
public class DbSettings
{
[ConfigKey("ConnectionString")] public string ConnStr { get; set; }
[ConfigKey("MaxPoolSize")] public int MaxPool { get; set; } = 100;
}
// 掃描屬性特性,綁定配置源
public class UserDto
{
[Required, StringLength(50)] public string Name { get; set; }
[Range(18, 120)] public int Age { get; set; }
[EmailAddress] public string Email { get; set; }
}
// Validator 遍歷屬性特性執行驗證邏輯
[AttributeUsage(AttributeTargets.Method, Inherited = false)]
public class CacheableAttribute : Attribute
{
public string KeyPrefix { get; set; }
public int TtlSeconds { get; set; } = 300;
}
// 切面攔截器讀取特性參數生成緩存 Key、設置 TTL
Roles = "Admin,User")。[Transaction] 派生類不應自動繼承事務邊界,顯式標注更清晰。[GenerateSerializer] (MessagePack)、[ReactComponent] (Blazor)、[Observable] (MVVM 工具包)。ISourceGenerator → context.SyntaxProvider.CreateSyntaxProvider 篩選帶特性節點 → 生成代碼注入編譯。Attribute 是 C# **聲明式編程**的核心機制。從 [Obsolete] 到 Source Generator 驅動的編譯期元編程,其本質始終是:**在不修改業務邏輯代碼的前提下,向框架/工具/編譯器傳遞結構化意圖**。掌握 AttributeUsage 三維控制、繼承語義、高性能反射檢索與反模式規避,能讓你設計出優雅、可擴展、工具友好的框架級 API。