免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1202 | 回复: 0
打印 上一主题 下一主题

Attribute.GetCustomAttribute 方法 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2011-12-20 09:44 |只看该作者 |倒序浏览
Attribute.GetCustomAttribute 方法 (MemberInfo, Type, Boolean)
检索应用于类型的成员的自定义属性的数组。参数指定成员、要搜索的自定义属性的类型以及是否搜索成员的祖先。

参数

element
一个从 MemberInfo 类派生的对象,该类描述类的构造函数、事件、字段、方法或属性成员。

attributeType
要搜索的自定义属性的类型或基类型。

inherit
如果为 true,则指定还在 element 的祖先中搜索自定义属性。

返回值

一个引用,指向应用于 element 的 attributeType 类型的单个自定义属性;如果没有此类属性,则为 空引用(在 Visual Basic 中为 Nothing)。

using System; using System.Reflection; namespace IsDef4CS { public class TestClass { // Assign the Obsolete attribute to a method. [Obsolete("This method is obsolete. Use Method2 instead.")] public void Method1() {} public void Method2() {} } public class DemoClass { static void Main(string[] args) { // Get the class type to access its metadata. Type clsType = typeof(TestClass); // Get the MethodInfo object for Method1. MethodInfo mInfo = clsType.GetMethod("Method1"); // See if the Obsolete attribute is defined for this method. bool isDef = Attribute.IsDefined(mInfo, typeof(ObsoleteAttribute)); // Display the result. Console.WriteLine("The Obsolete Attribute {0} defined for {1} of class {2}.", isDef ? "is" : "is not", mInfo.Name, clsType.Name); // If it's defined, display the attribute's message. if (isDef) { ObsoleteAttribute obsAttr = (ObsoleteAttribute)Attribute.GetCustomAttribute( mInfo, typeof(ObsoleteAttribute)); if (obsAttr != null) Console.WriteLine("The message is: \"{0}\".", obsAttr.Message); else Console.WriteLine("The message could not be retrieved."); } } } } /* * Output: * The Obsolete Attribute is defined for Method1 of class TestClass. * The message is: "This method is obsolete. Use Method2 instead.". */

您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP