最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
在.NET运行时了解类型信息(3) Paul_Ni(原作)-Windows开发-.NET教程-
时间:2022-07-02 11:17:39 编辑:袖梨 来源:一聚教程网
访问自定义属性
当属性与程序元素相关联后,可以使用反射来查询它们是否存在以及它们的值。用于查询属性的主要反射方法包含在 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() 方法)内是否可见和可以访问。
当属性与程序元素相关联后,可以使用反射来查询它们是否存在以及它们的值。用于查询属性的主要反射方法包含在 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() 方法)内是否可见和可以访问。
相关文章
- 腾讯视频网页版入口在哪-腾讯视频网页版入口链接 02-10
- 歪歪漫画最新入口地址:2026年热门韩漫同步连载中 02-10
- 蛙漫2台版入口网页最新版-蛙漫2台版入口网页最新访问链接 02-10
- 创游世界网页版入口-创游世界网页版直达链接 02-10
- 12360火车票余票查询-如何在线查询火车票余票 02-10
- 抖音官网网页版入口-抖音网页版在线观看链接 02-10