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

[你必須知道的 .NET] 第三回:特性 與 屬性 的歷史糾葛、定義、規則與實戰應用

     編輯:關於C#

名詞釐清:Attribute ≠ Property

中文慣稱英文本質用途
特性Attribute繼承 System.Attribute 的類別,編譯期嵌入中繼資料序列化控制、編譯器指令、設計模式標記、運行期反射讀取
屬性Property類別成員,封裝 get/set 存取器資料封裝、繫結、驗證、介面契約

MSDN 早期將 Attribute 譯為「屬性」造成混淆,現建議統稱 Attribute 為「特性」。

Attribute 通用規則

  • 適用目標:assembly、module、type、property、event、field、method、param、return
  • 語法:[AttributeName]、[AttributeName(...)]、[Attr1, Attr2]、[Attr1(), Attr2()]
  • 前綴消除歧義:[assembly: MyAttr]、[module: MyAttr]、[type: MyAttr]、[method: MyAttr]、[property: MyAttr]、[event: MyAttr]、[field: MyAttr]、[param: MyAttr]、[return: MyAttr]
  • 實例化時機:編譯期,非運行期
  • 命名慣例:類別名以 Attribute 結尾(如 ObsoleteAttribute),使用時可省略
  • 繼承規則:AttributeUsage(Inherited=true) 控制衍生類別是否繼承
  • 多重套用:AllowMultiple=true
  • 所有非抽象 Attribute 必須 public

內建經典 Attribute

Attribute用途關鍵屬性
AttributeUsage控制自訂 Attribute 套用規則ValidOn、AllowMultiple、Inherited
Flags列舉視為位元旗標ToString() 輸出 "A, B" 而非數值
DllImport呼叫非託管 DLLEntryPoint、CallingConvention、CharSet
Serializable標記型別可序列化配合 ISerializable 自訂
Conditional條件編譯方法呼叫DEBUG、TRACE 等符號控制
Obsolete標記過時成員Message、IsError
Description/Category/DefaultValue/Browsable設計工具屬性格柵顯示控制屬性視窗分組、預設值、可見性

自訂 Attribute 完整範例


[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class TestAttribute : Attribute {
    public string Message { get; }
    public TestAttribute(string msg) => Message = msg;
    public void RunTest() => Console.WriteLine($"TestAttribute: {Message}");
}

// 套用
[Test("驗證邏輯")]
public class MyClass {
    [Test("前置條件")]
    public void DoWork() { }
}

// 反射讀取
var attr = (TestAttribute)Attribute.GetCustomAttribute(typeof(MyClass), typeof(TestAttribute));
attr?.RunTest();

var method = typeof(MyClass).GetMethod("DoWork");
var attrs = method.GetCustomAttributes();
foreach (var a in attrs) a.RunTest();

實戰應用場景

  1. 序列化控制:[DataContract]/[DataMember]、[JsonPropertyName]
  2. 驗證框架:[Required]/[StringLength]/[Range] (DataAnnotations)
  3. 依賴注入:[Inject]/[Service] 標記注入點
  4. 單元測試:[Test]/[TestCase]/[Ignore] (NUnit/xUnit)
  5. ORM 映射:[Table]/[Column]/[Key] (EF/Dapper)
  6. AOP 截取點:[Log]/[Cache]/[Transaction] (PostSharp/DynamicProxy)

結語

Attribute 是 .NET 中繼資料驅動程式設計的基石。掌握其定義規則、反射讀取與內建/自訂應用,能讓架構更乾淨、擴充性更強。下一回將深入探討「類別與結構」的記憶體模型差異。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved