| 屬性 | 型別 | 預設值 | 說明 |
ValidOn | AttributeTargets | AttributeTargets.All | 限制特性可套用的程式碼元素類型 |
AllowMultiple | bool | false | 是否允許同一元素套用多次 |
Inherited | bool | true | 衍生類別是否繼承此特性 |
完整範例
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,結果為空
| AllowMultiple | Inherited | Derived 查詢結果 |
| false | false | 無特性 |
| true | false | 無特性 |
| false | true | 僅 Derived 自己的 (覆蓋 Base) |
| true | true | Base + Derived 兩者皆有 |
繼承查詢細節
GetCustomAttributes(typeof(T), inherit: true):inherit=true 會走繼承鏈,但仍受 Inherited 屬性控制。
MemberInfo.IsDefined(typeof(T), inherit):同理。
- 介面實作不視為繼承,
Inherited 不影響介面成員特性查詢。
最佳實務建議
- 預設
AllowMultiple = false、Inherited = true 符合多數情境。
- 標記式特性 (如
[Serializable]) 設 AllowMultiple = false、Inherited = true。
- 資訊性特性 (如
[Help]) 視需求決定 AllowMultiple。
- 組件層級特性 (
[assembly: ...]) 無繼承概念,Inherited 無效。
- 上一篇文章: C# Attribute 特性入門指南 (一):預定義特性與自訂特性建立
- 下一篇文章: C# 2.0 Iterator 迭代器改進與編譯器實現原理深度解析
Copyright ©
程式碼之家 All Rights Reserved