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

   2024-10-01 7990
核心提示:在C#中,可以使用GetCustomAttributes方法来获取指定成员(如类、方法、属性等)的自定义属性。该方法返回一个Attribute数组,表

在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方法的返回值上。获取到返回值属性后,我们遍历输出了该属性的信息。

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号