溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

自定義C#特性與元數(shù)據(jù)統(tǒng)計

發(fā)布時間:2024-09-06 10:47:35 來源:億速云 閱讀:80 作者:小樊 欄目:編程語言

在C#中,特性(Attribute)是一種用于為代碼添加元數(shù)據(jù)的機(jī)制

以下是如何創(chuàng)建自定義特性并將其應(yīng)用于類和方法的示例:

  1. 首先,創(chuàng)建一個自定義特性類。這個類需要繼承自System.Attribute。
using System;

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
public class CustomMetadataAttribute : Attribute
{
    public string Key { get; set; }
    public string Value { get; set; }

    public CustomMetadataAttribute(string key, string value)
    {
        Key = key;
        Value = value;
    }
}
  1. 然后,將自定義特性應(yīng)用于類和方法。
using System;

[CustomMetadata("ClassKey", "ClassValue")]
public class MyClass
{
    [CustomMetadata("MethodKey", "MethodValue")]
    public void MyMethod()
    {
        // ...
    }
}
  1. 最后,使用反射來獲取特性信息并進(jìn)行統(tǒng)計。
using System;
using System.Reflection;

class Program
{
    static void Main(string[] args)
    {
        Type type = typeof(MyClass);

        // 獲取類上的特性
        object[] classAttributes = type.GetCustomAttributes(typeof(CustomMetadataAttribute), false);
        foreach (CustomMetadataAttribute attribute in classAttributes)
        {
            Console.WriteLine($"Class - Key: {attribute.Key}, Value: {attribute.Value}");
        }

        // 獲取方法上的特性
        MethodInfo methodInfo = type.GetMethod("MyMethod");
        object[] methodAttributes = methodInfo.GetCustomAttributes(typeof(CustomMetadataAttribute), false);
        foreach (CustomMetadataAttribute attribute in methodAttributes)
        {
            Console.WriteLine($"Method - Key: {attribute.Key}, Value: {attribute.Value}");
        }
    }
}

運(yùn)行上述代碼,你將看到以下輸出:

Class - Key: ClassKey, Value: ClassValue
Method - Key: MethodKey, Value: MethodValue

這樣,你就可以根據(jù)需要對特性進(jìn)行統(tǒng)計和分析。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI