Attribute.GetCustomAttribute 方法

3183阅读 0评论2011-04-18 I_am_tbag
分类:嵌入式

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

上一篇:.net IRequiresSessionState
下一篇:lion中启动mysql