首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# Attribute 特性入門指南 (二):AttributeUsage 控制套用規則深度解析

     編輯:關於C語言

AttributeUsage 三大屬性

完整範例


using System;

// 僅允許套用在類別上、不可重複、不繼承
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
public class HelpAttribute : Attribute
{
    public HelpAttribute(string description) => Description = description;
    public string Description { get; }
}

ValidOn 實測


[Help("類別說明")]
public class MyClass
{
    [Help("方法說明")] // 編譯錯誤:Attribute 'Help' is not valid on this declaration type. It is valid on 'class' declarations only.
    public void MyMethod() { }
}

AllowMultiple 實測


// AllowMultiple = false (預設)
[Help("第一個")]
[Help("第二個")] // 編譯錯誤:Duplicate 'Help' attribute
public class MyClass { }

// 改為 true
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
public class HelpAttribute : Attribute { ... }

[Help("第一個")]
[Help("第二個")] // 合法
public class MyClass { }

Inherited 實測:四種組合


[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
public class HelpAttribute : Attribute { ... }

[Help("Base")]
public class Base { }

public class Derived : Base { }

// 查詢 Derived 的 HelpAttribute
var attrs = typeof(Derived).GetCustomAttributes(typeof(HelpAttribute), true); // true = 含繼承
// 因 Inherited=false,結果為空
屬性型別預設值說明
ValidOnAttributeTargetsAttributeTargets.All限制特性可套用的程式碼元素類型
AllowMultipleboolfalse是否允許同一元素套用多次
Inheritedbooltrue衍生類別是否繼承此特性
AllowMultipleInheritedDerived 查詢結果
falsefalse無特性
truefalse無特性
falsetrue僅 Derived 自己的 (覆蓋 Base)
truetrueBase + Derived 兩者皆有

繼承查詢細節

  • GetCustomAttributes(typeof(T), inherit: true):inherit=true 會走繼承鏈,但仍受 Inherited 屬性控制。
  • MemberInfo.IsDefined(typeof(T), inherit):同理。
  • 介面實作不視為繼承,Inherited 不影響介面成員特性查詢。

最佳實務建議

  1. 預設 AllowMultiple = false、Inherited = true 符合多數情境。
  2. 標記式特性 (如 [Serializable]) 設 AllowMultiple = false、Inherited = true。
  3. 資訊性特性 (如 [Help]) 視需求決定 AllowMultiple。
  4. 組件層級特性 ([assembly: ...]) 無繼承概念,Inherited 無效。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved