| 英文 | 中文建議 | 本質 |
| Property | 屬性 | 封裝欄位的 get/set 存取器 |
| Attribute | 標注/特性標記 | 掛載中繼資料的類別(繼承 System.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