萬盛學電腦網

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

C# Property 與 Attribute 深度解析:特性與屬性的語義差異、定義與反射查詢實戰

C# 中 Property(屬性/特性) 與 Attribute(屬性/標注) 中文易混淆,實為完全不同機制。Property 是類別成員的存取器;Attribute 是編譯時/執行時掛載在類型/成員上的中繼資料,可被編譯器識別或反射讀取。本文以《C# 技術揭秘》範例深度解析 Attribute 定義、套用與反射查詢。

術語釐清

自訂 Attribute 定義範例:登錄機碼映射

public enum RegHives {
    HKEY_CLASSES_ROOT, HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE,
    HKEY_USERS, HKEY_CURRENT_CONFIG
}

public class RegKeyAttribute : Attribute {
    public RegKeyAttribute(RegHives hive, string valueName) {
        Hive = hive; ValueName = valueName;
    }
    public RegHives Hive { get; set; }
    public string ValueName { get; set; }
}

套用 Attribute 於類別/方法

[RemoteObject(RemoteServers.COSETTE)]
class MyRemotableClass { }

class SomeClass {
    [Transactionable] public void Foo() {}
    public void Bar() {}
    [Transactionable] public void Goo() {}
}

反射查詢類別層級 Attribute

Type type = typeof(MyRemotableClass);
foreach (Attribute attr in type.GetCustomAttributes(true)) {
    var remoteAttr = attr as RemoteObjectAttribute;
    if (remoteAttr != null)
        Console.WriteLine("Create this object on {0}.", remoteAttr.Server);
}
// 輸出: Create this object on COSETTE.

反射查詢方法層級 Attribute

Type type = Type.GetType("MethodAttribs.SomeClass");
foreach (MethodInfo mi in type.GetMethods()) {
    foreach (Attribute attr in mi.GetCustomAttributes(true)) {
        if (attr is TransactionableAttribute)
            Console.WriteLine("{0} is transactionable.", mi.Name);
    }
}
// 輸出: Foo is transactionable. / Goo is transactionable.

命名慣例與編譯器行為

  • Attribute 類別命名以 Attribute 結尾(如 RemoteObjectAttribute)
  • 套用時可省略尾綴:[RemoteObject(...)]
  • 編譯器先找精確名稱,再嘗試加 Attribute 尾綴搜尋

Attribute 核心價值

  • 設計時資訊:文檔、序列化規則、資料庫映射
  • 編譯時條件:Obsolete、Conditional、Serializable
  • 執行時行為:DI 容器註冊、AOP 切面、MVC 路由、單元測試標記
copyright © 萬盛學電腦網 all rights reserved
英文中文建議本質
Property屬性封裝欄位的 get/set 存取器
Attribute標注/特性標記掛載中繼資料的類別(繼承 System.Attribute)