• 博客园logo
  • 会员
  • 周边
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
编写人生
写写代码,写写人生
博客园    首页    新随笔    联系   管理    订阅  订阅
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为什么这样设计,造成我现在的混乱。
posted on 2005-08-25 14:11  编写人生  阅读(2400)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3