If you do not retrieve the information of a custom property and perform operations on it, it is meaningless to define the custom property and place it in the source code. C # has a reflection system that can be used to retrieve information defined with custom attributes. The main method is getcustomattributes, which returns an array of objects, which are equivalent to source code properties at runtime. This method has multiple overloaded versions.
Attribute specifications, such:
Code
[Author ("H. Ackerman", version = 1.1)]
Class sampleclass
It is equivalent:
Code
Author anonymousauthorobject = new author ("H. Ackerman ");
Anonymousauthorobject. Version = 1.1;
However, this code is not executed until sampleclass is queried to obtain attributes. When getcustomattributes is called for sampleclass, an author object is constructed and initialized in the preceding method. If the class has other properties, the other property objects are constructed in a similar way. Then getcustomattributes returns the author object and any other attribute objects in the array. Then, you can iterate on the array, determine the attributes applied based on the type of each array element, and extract information from the attribute object.
Example
The following is a complete example. Define a custom attribute, apply it to several objects, and search by reflection.
Code
[System. attributeusage (system. attributetargets. Class |
System. attributetargets. struct,
Allowmultiple = true) // multiuse attribute
]
Public class Author: system. Attribute
{
String name;
Public double version;
Public author (string name)
{
This. Name = Name;
Version = 1.0; // Default Value
}
Public String getname ()
{
Return name;
}
}
[Author ("H. Ackerman")]
Private class firstclass
{
//
}
// No author attribute
Private class secondclass
{
//
}
[Author ("H. Ackerman"), author ("M. Knott", version = 2.0)]
Private class thirdclass
{
//
}
Class testauthorattribute
{
Static void main ()
{
Printauthorinfo (typeof (firstclass ));
Printauthorinfo (typeof (secondclass ));
Printauthorinfo (typeof (thirdclass ));
}
Private Static void printauthorinfo (system. type T)
{
System. Console. writeline ("author information for {0}", t );
System. Attribute [] attrs = system. Attribute. getcustomattributes (t); // reflection
Foreach (system. Attribute ATTR in attrs)
{
If (ATTR is author)
{
Author A = (author) ATTR;
System. Console. writeline ("{0}, version {1: f}", A. getname (), A. version );
}
}
}
}
Output:
Author information for firstclass
H. Ackerman, Version 1.00.
Author information for secondclass
Author information for thirdclass
H. Ackerman, Version 1.00.
M. Knott, version 2.00