【www.gdgbn.com--网络相关】

访问自定义属性
当属性与程序元素相关联后,可以使用反射来查询它们是否存在以及它们的值。用于查询属性的主要反射方法包含在 System.Reflection.MemberInfo.GetCustomAttributes 和 System.Reflection.Assembly.GetCustomAttributes 中。
自定义属性的可访问性根据附加该属性的程序集来进行检查。这相当于检查附加自定义属性的程序集中的类型上的方法是否可以调用自定义属性的构造函数。
诸如 System.Reflection.Assembly.GetCustomAttributes(Type, Boolean) 等方法检查类型参数的可见性和可访问性。只有包含用户定义类型的程序集中的代码才能使用 GetCustomAttributes 检索该类型的自定义属性。
以下代码示例是典型的自定义属性设计模式。它说明运行库自定义属性反射模型。
[C#]
System.DLL
public class DescriptionAttribute : Attribute
{
}

     System.Web.DLL
     internal class MyDescriptionAttribute : DescriptionAttribute
     {
     }

     public class LocalizationExtenderProvider
     {
        [MyDescriptionAttribute(...)]
        public CultureInfo GetLanguage(...)
     {
     }
}
如果试图为附加到 GetLanguage 方法的公共自定义属性类型 DescriptionAttribute 检索自定义属性,运行库将执行以下操作: 运行库检查 Type.GetCustomAttributes(Type type) 的 DescriptionAttribute 类型参数是否为公共的,并检查其是否可见或可以访问。
 运行库检查从 DescriptionAttribute 导出的用户定义类型 MyDescriptionAttribute 在 System.Web.DLL 程序集(它在该程序集中附加到 GetLanguage() 方法)内是否可见和可以访问。

本文来源:http://www.gdgbn.com/jiaocheng/4760/