C#中GetCustomAttributes如何獲取返回值屬性

c#
小樊
97
2024-08-19 13:13:32

在C#中,可以使用GetCustomAttributes方法來(lái)獲取指定成員(如類、方法、屬性等)的自定義屬性。該方法返回一個(gè)Attribute數(shù)組,表示指定成員上應(yīng)用的所有自定義屬性。

以下是一個(gè)示例代碼,用于獲取返回值屬性:

using System;
using System.Reflection;

class Program
{
    static void Main()
    {
        MethodInfo methodInfo = typeof(MyClass).GetMethod("MyMethod");
        
        // 獲取返回值屬性
        object[] returnAttributes = methodInfo.ReturnTypeCustomAttributes.GetCustomAttributes(true);
        
        foreach (object attribute in returnAttributes)
        {
            Console.WriteLine(attribute.ToString());
        }
    }
}

class MyClass
{
    [MyCustomAttribute("Custom attribute")]
    public int MyMethod()
    {
        return 0;
    }
}

[AttributeUsage(AttributeTargets.ReturnValue)]
class MyCustomAttribute : Attribute
{
    public MyCustomAttribute(string message)
    {
        Message = message;
    }

    public string Message { get; }
}

在上面的示例中,我們通過反射獲取了MyClass類中的MyMethod方法,并使用GetCustomAttributes方法來(lái)獲取返回值屬性。在這個(gè)例子中,我們定義了一個(gè)自定義屬性MyCustomAttribute,并將其應(yīng)用在MyMethod方法的返回值上。獲取到返回值屬性后,我們遍歷輸出了該屬性的信息。

0