温馨提示×

C#中GetCustomAttributes如何获取返回值属性

c#
小樊
97
2024-08-19 13:13:32
栏目: 编程语言

在C#中,可以使用GetCustomAttributes方法来获取指定成员(如类、方法、属性等)的自定义属性。该方法返回一个Attribute数组,表示指定成员上应用的所有自定义属性。

以下是一个示例代码,用于获取返回值属性:

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方法来获取返回值属性。在这个例子中,我们定义了一个自定义属性MyCustomAttribute,并将其应用在MyMethod方法的返回值上。获取到返回值属性后,我们遍历输出了该属性的信息。

0