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类的自定义属性,并将其值打印出来。可以看到,两种方法都能够正确获取到自定义属性的值。

相关内容

热门资讯

aapoker透明挂!wepo... aapoker透明挂!wepower伙牌,(aa poker)切实存在有挂(详细辅助透明教程);超受...
wepoke辅助!德州软件工具... 您好,wepoke辅助这款游戏可以开挂的,确实是有挂的,需要了解加微【136704302】很多玩家在...
德州ai人工智能!pokerm... 德州ai人工智能!pokermastersteam外挂,(wePoke)好像真的有挂(详细辅助黑科技...
wpk透视辅助工具!aapok... wpk透视辅助工具!aapoker俱乐部后天可以操作吗,(WepokE)果然真的有挂(详细辅助揭秘教...
aapoker发牌机制!wep... aapoker发牌机制新手教程相关信息汇总(需添加指定Q群1067239143获取下载链接);aap...
wepoke辅助插件!wpk俱... 相信很多朋友都在电脑上玩过wepoke辅助插件吧,但是很多朋友都在抱怨用电脑玩起来不方便。为此小编给...
wepokeai机器人!wep... 一、wepokeai机器人简介了解软件请加微:136704302wepokeai机器人是一款在线扑克...
德州ai辅助软件!wpk俱乐部... 1、德州ai辅助软件!wpk俱乐部系统,(德州俱乐部)先前真的是有挂(详细辅助2025教程);详细教...
wepoke智能ai!wpk微... 1、wepoke智能ai!wpk微扑克外挂事件,(wePOke)最初是真的有挂(详细辅助2025新版...