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

C# Attribute 特性系統:預定義/自定義/AttributeUsage/Conditional/Obsolete

     編輯:C# 入門

C# Attribute 特性系統:預定義/自定義/AttributeUsage/Conditional/Obsolete

Attribute 為程序元素(類、方法、組件等)附加聲明性元數據,編譯時嵌入元數據,運行時通過反射讀取。

語法

[AttributeName(positionalParams, namedParam = value)]
targetElement

三大預定義 Attribute

Attribute用途關鍵參數
AttributeUsage限制自定義 Attribute 適用目標validOn(AttributeTargets), AllowMultiple, Inherited
Conditional條件編譯方法調用conditionalSymbol (如 "DEBUG")
Obsolete標記過時成員,編譯警告/錯誤message, isError

示例:Conditional 調試輸出

#define DEBUG
[Conditional("DEBUG")]
static void Log(string msg) => Console.WriteLine(msg);
// 僅 DEBUG 定義時調用生效,Release 版本調用點被移除

示例:Obsolete 遷移提示

[Obsolete("Use NewMethod instead", true)]  // true=編譯錯誤
static void OldMethod() {}
static void NewMethod() {}

自定義 Attribute 四步驟

  1. 繼承 System.Attribute 聲明類
  2. 構造函數接收 positional 參數,屬性接收 named 參數
  3. 目標元素上應用 [MyAttr(...)]
  4. 反射讀取:type.GetCustomAttributes()

完整示例:DeBugInfo

[AttributeUsage(Class|Constructor|Field|Method|Property, AllowMultiple=true)]
public class DeBugInfo : Attribute {
    public int BugNo { get; }
    public string Developer { get; }
    public string LastReview { get; }
    public string Message { get; set; }
    public DeBugInfo(int no, string dev, string review) { ... }
}
[DeBugInfo(45, "Zara", "12/8/2012", Message="Mismatch")]
class Rectangle { ... }

下章將演示反射讀取此元數據。

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