Attribute.GetCustomAttributes和MemberInfo.GetCustomAttributes可以互换使用吗?
创始人
2024-09-21 22:00:24
0

Attribute.GetCustomAttributes和MemberInfo.GetCustomAttributes可以互换使用,因为MemberInfo是Attribute的父类。

下面是一个示例代码,演示了如何互换使用这两个方法:

using System;
using System.Reflection;

[AttributeUsage(AttributeTargets.Class)]
public class MyAttribute : Attribute
{
    public MyAttribute(string value)
    {
        this.Value = value;
    }

    public string Value { get; set; }
}

[MyAttribute("Hello")]
public class MyClass
{
    public string MyProperty { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        // 使用Attribute.GetCustomAttributes获取MyClass的所有自定义属性
        Attribute[] attributes1 = Attribute.GetCustomAttributes(typeof(MyClass));

        foreach (Attribute attribute in attributes1)
        {
            if (attribute is MyAttribute)
            {
                MyAttribute myAttribute = (MyAttribute)attribute;
                Console.WriteLine(myAttribute.Value);
            }
        }

        Console.WriteLine("------------------");

        // 使用MemberInfo.GetCustomAttributes获取MyClass的所有自定义属性
        MemberInfo memberInfo = typeof(MyClass);
        Attribute[] attributes2 = Attribute.GetCustomAttributes(memberInfo);

        foreach (Attribute attribute in attributes2)
        {
            if (attribute is MyAttribute)
            {
                MyAttribute myAttribute = (MyAttribute)attribute;
                Console.WriteLine(myAttribute.Value);
            }
        }
    }
}

输出结果为:

Hello
------------------
Hello

以上代码示例中,我们定义了一个自定义属性MyAttribute,然后给MyClass类应用了这个自定义属性。接下来,我们使用Attribute.GetCustomAttributes方法和MemberInfo.GetCustomAttributes方法来获取MyClass类的自定义属性,并将其值打印出来。可以看到,两种方法都能够正确获取到自定义属性的值。

相关内容

热门资讯

围绕透视问题!智星德州插件怎么... 围绕透视问题!智星德州插件怎么下载,德普辅助app,其实真的是有挂(有挂方法)1、进入游戏-大厅左侧...
黑科技技巧!德普之星私人局辅助... 黑科技技巧!德普之星私人局辅助免费,德扑之星怎么开辅助,总是是有挂(有挂方法)1、起透看视 德普之星...
今日!wepoker辅助器安装... 今日!wepoker辅助器安装包,德普之星透视辅助软件,原来真的是有挂(真是有挂)所有人都在同一条线...
备受关注的!hhpoker辅助... 备受关注的!hhpoker辅助靠谱吗,德扑之星透视免费,一直存在有挂(确实有挂)1、德扑之星透视免费...
黑科技教程!wpk私人局辅助是... 黑科技教程!wpk私人局辅助是真的吗,德扑之星透视软件免费入口官网,好像确实有挂(有挂猫腻)1、这是...
据统计!wepoker辅助透视... 据统计!wepoker辅助透视软件,德普之星私人局透视,其实确实有挂(有挂方法)德普之星私人局透视辅...
备受关注的!wepoker怎么... 备受关注的!wepoker怎么挂底牌,德扑之星怎么设置埋牌,一贯是真的有挂(有挂头条)小薇(辅助器软...
出乎意料的是!德普之星透视免费... 出乎意料的是!德普之星透视免费,德扑圈透视,一直真的有挂(有挂详情)1、许多玩家不知道德普之星透视免...
反观!hh poker透视器下... 反观!hh poker透视器下载,德扑之星辅助工具如何打开,真是是有挂(有挂分析)1、操作简单,无需...
目前!德普之星怎么开辅助,德扑... 目前!德普之星怎么开辅助,德扑之星辅助器,竟然是有挂(有挂秘籍)所有人都在同一条线上,像星星一样排成...