Information Technology Reference
In-Depth Information
Using the GetCustomAttributes Method
The GetCustomAttributes method returns an array of the attributes applied to a construct.
The actual object returned is an array of object s, which you must then cast to the correct
attribute type.
￿
￿
The Boolean parameter specifies whether to search the inheritance tree to find the
attribute.
object[] AttArr = t.GetCustomAttributes(false);
￿When the GetCustomAttributes method is called, an instance of each attribute associ-
ated with the target is created.
The following code uses the same attribute and class declarations as the previous exam-
ple. But in this case, it doesn't just determine whether an attribute is applied to the class.
Instead, it retrieves an array of the attributes applied to the class and cycles through them,
printing out their member values.
static void Main( )
{
MyClass mc = new MyClass();
Type t = mc.GetType();
object[] AttArr = t.GetCustomAttributes(false);
foreach (Attribute a in AttArr)
{
MyAttributeAttribute attr = a as MyAttributeAttribute;
if (null != attr)
{
Console.WriteLine("Description : {0}", attr.Description);
Console.WriteLine("Version Number : {0}", attr.VersionNumber);
Console.WriteLine("Reviewer ID : {0}", attr.ReviewerID);
}
}
}
Search WWH ::




Custom Search