Chinaunix首页 | 论坛 | 博客
  • 博客访问: 474337
  • 博文数量: 112
  • 博客积分: 5696
  • 博客等级: 大校
  • 技术积分: 1720
  • 用 户 组: 普通用户
  • 注册时间: 2007-08-17 09:58
文章分类

全部博文(112)

文章存档

2011年(22)

2010年(28)

2009年(21)

2008年(41)

分类: 嵌入式

2011-04-18 00:40:55

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.". */

阅读(3087) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~