MemberInfo.GetCustomAttributes和MemberDescriptor.Attributes获取特性的不同

注:为区分Attribute和Property翻译的不同,Property翻译为属性,Attribute翻译为特性。

在对对象进行反射操作时,有俩个主要的方式处理:一个是System.Reflection命名空间下的一组*Info类,一个是System.ComponentModel命名空间下的一组*Descriptor类。他们的区别可以参考MSDN的相关章节。

这里讨论的是具体到MemberInfo.GetCustomAttributes和MemberDescriptor.Attributes获取特性的不同,他们都返回成员的特性,但获取的结果不同。
假设有下面俩个类:
    class A{
        
private B _b;

        
public B B {
            
get return _b; }
            
set { _b = value; }
        }

    }


    [System.ComponentModel.Description(
"注释信息")]
    
class B : A {
    }

这里的A有一个属性B,类型是B.
现在使用MemberInfo.GetCustomAttributes获取B属性的标记
            foreach (Attribute att in typeof(A).GetProperty("B").GetCustomAttributes(false)) {
                Console.WriteLine(att.ToString());
            }

我们发现没有任何输出,因为我们看见B属性上的确没有任何“特性”。

但我们现在转成使用MemberDescriptor.Attributes获取特性。
            foreach (Attribute att in System.ComponentModel.TypeDescriptor.GetProperties(typeof(A))["B"].Attributes) {
                Console.WriteLine(att.ToString());
            }

输出的结果竟然是:
System.ComponentModel.DescriptionAttribute

这说明这个函数将属性的返回类型的标记也作为输出部分了,但我实在不明白MS为什么这样设计,造成我现在的混乱。
原文地址:https://www.cnblogs.com/tansm/p/222640.html