萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

C# Attribute (特性) 完整指南:從預定義到自定義特性、AttributeUsage 控制與反射檢索實戰

前言:特性是「聲明式元數據」的基石

C# 特性 (Attribute) 允許在編譯時將元數據附加到程序元素 (類、方法、屬性、參數、程序集等),運行時通過反射讀取,驅動框架行為(序列化、驗證、路由、依賴注入、AOP、代碼生成)。本文系統講解預定義特性、自定義特性開發、AttributeUsage 控制、繼承規則、反射檢索模式與實戰反模式。

一、預定義特性速查

特性命名空間作用典型場景
[Obsolete]System標記過時成員,編譯警告/錯誤API 版本演進
[Conditional]System.Diagnostics條件編譯調用Debug.Log、Trace、契約檢查
[Serializable]System標記類型可序列化BinaryFormatter、Remoting (舊)
[AttributeUsage]System控制自定義特性使用規則元特性,必學
[CallerMemberName] / CallerFilePath / CallerLineNumberSystem.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);

三、AttributeUsage 三大控制維度

屬性類型默認值說明
ValidOnAttributeTargets (Flags 枚舉)All允許標注的程序元素:Class, Struct, Method, Property, Field, Parameter, Assembly, Module, Enum, Interface, Delegate, ReturnValue, GenericParameter 等
AllowMultipleboolfalsetrue 允許同一元素多次應用同一特性
Inheritedbooltruetrue 允許派生類繼承基類特性 (僅類/接口繼承有效,成員重寫不繼承)

3.1 組合示例

[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 僅影響**類/接口繼承鏈**的查找,**不影響**方法重寫、接口實現、屬性覆蓋等成員級繼承(成員級需手動遍歷)。

五、反射檢索模式大全

5.1 類/結構/枚舉/接口/委托

var attrs = typeof(T).GetCustomAttributes(inherit: true);
var attr  = typeof(T).GetCustomAttribute(inherit: true); // 單個
bool has  = typeof(T).IsDefined(typeof(TAttribute), inherit: true);

5.2 方法/構造函數/屬性/字段/事件/參數/返回值

// 方法
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();

5.3 高性能緩存模式 (避免重複反射)


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());
}

六、實戰場景:三大經典應用模式

6.1 配置映射 (如 appsettings.json → POCO)


[ConfigSection("Database")]
public class DbSettings
{
    [ConfigKey("ConnectionString")] public string ConnStr { get; set; }
    [ConfigKey("MaxPoolSize")] public int MaxPool { get; set; } = 100;
}

// 掃描屬性特性,綁定配置源

6.2 驗證框架 (DataAnnotations / FluentValidation 核心)


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 遍歷屬性特性執行驗證邏輯

6.3 AOP 攔截點標記 (如事務、緩存、限流)


[AttributeUsage(AttributeTargets.Method, Inherited = false)]
public class CacheableAttribute : Attribute
{
    public string KeyPrefix { get; set; }
    public int TtlSeconds { get; set; } = 300;
}

// 切面攔截器讀取特性參數生成緩存 Key、設置 TTL

七、反模式與避坑指南

  1. 特性邏輯過重:特性僅應承載**聲明式配置數據**,具體業務邏輯放在處理器/攔截器中。
  2. 濫用 AllowMultiple=true:導致檢索複雜化,優先設計為複合屬性 (如 Roles = "Admin,User")。
  3. 忽略 Inherited=false 的語義:基類標記 [Transaction] 派生類不應自動繼承事務邊界,顯式標注更清晰。
  4. 運行時大量反射無緩存:啟動掃描階段構建緩存,熱路徑直接讀取緩存。
  5. 特性構造函數參數過多:改用命名參數屬性,構造函數僅保留必填項。

八、Source Generator 時代的特性新玩法 (C# 9+)

  • 編譯期讀取特性,**生成 C# 代碼** 而非運行時反射,零反射開銷、AOT 友好。
  • 典型:[GenerateSerializer] (MessagePack)、[ReactComponent] (Blazor)、[Observable] (MVVM 工具包)。
  • 開發步驟:實現 ISourceGenerator → context.SyntaxProvider.CreateSyntaxProvider 篩選帶特性節點 → 生成代碼注入編譯。

結語

Attribute 是 C# **聲明式編程**的核心機制。從 [Obsolete] 到 Source Generator 驅動的編譯期元編程,其本質始終是:**在不修改業務邏輯代碼的前提下,向框架/工具/編譯器傳遞結構化意圖**。掌握 AttributeUsage 三維控制、繼承語義、高性能反射檢索與反模式規避,能讓你設計出優雅、可擴展、工具友好的框架級 API。

copyright © 萬盛學電腦網 all rights reserved