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

C# Attribute 特性入門指南 (一):預定義特性與自訂特性建立

     編輯:關於C語言

什麼是 Attribute

Attribute (特性) 是附加在程式碼元素 (類別、方法、屬性、參數、組件等) 上的宣告式中繼資料。編譯器將其編譯進組件中繼資料,執行期透過反射讀取,實現「自描述組件」。

常用預定義特性

特性用途範例
[Obsolete]標記過時成員[Obsolete("請用 NewMethod", true)] (true=編譯錯誤)
[Serializable]標記可序列化[Serializable] public class Dto { }
[AttributeUsage]限制自訂特性套用目標見下文
[Conditional]條件編譯方法呼叫[Conditional("DEBUG")]
[CallerMemberName]自動取得呼叫者名稱參數預設值用於 Log/INotifyPropertyChanged

建立自訂特性

步驟 1:繼承 System.Attribute


using System;

public class HelpAttribute : Attribute
{
    public HelpAttribute(string description)
    {
        Description = description;
    }

    public string Description { get; }
    public string Url { get; set; } // 可選屬性 (named parameter)
}
  • 類別名慣例以 Attribute 結尾
  • 建構子參數 = 位置參數 (必要)
  • 公開屬性/欄位 = 命名參數 (選擇性)

步驟 2:套用特性


// 位置參數
[Help("這是一個範例類別")]
public class SampleClass { }

// 位置 + 命名參數
[Help("主要控制器", Url = "https://example.com/help")]
public class MainController { }

// 多個特性
[Serializable]
[Help("資料傳輸物件")]
public class UserDto { }

編譯器查找特性類別時,先找完整名稱,再嘗試加上 Attribute 後綴。

執行期讀取特性 (反射)


using System;
using System.Reflection;

var type = typeof(SampleClass);
var attrs = type.GetCustomAttributes(typeof(HelpAttribute), false);
foreach (HelpAttribute attr in attrs)
{
    Console.WriteLine($"Description: {attr.Description}");
    Console.WriteLine($"Url: {attr.Url ?? "N/A"}");
}

特性可套用的目標

AttributeTargets 列舉定義:

  • Assembly, Module (需放在檔案最上方 [assembly: ...])
  • Class, Struct, Enum, Interface, Delegate
  • Constructor, Method, Property, Field, Event, Parameter, ReturnValue, TypeParameter
  • All = 以上全部

下一篇預告

下一篇將深入 [AttributeUsage] 控制特性套用規則:ValidOn (目標限制)、AllowMultiple (是否可重複)、Inherited (是否繼承)。

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