Using system;
Using system. Collections. Generic;
Using system. text;
Using system. reflection;
Namespace testattributedemo
{
Class class2
{
Public Delegate voidTesthandle(String text); // delegate an event testhandle
Static voidTest1_onhandle(String text) // start with the event
{
System. Console. writeline (text );
}
[attributeusage (attributetargets. class | attributetargets. constructor | attributetargets. method | attributetargets. event)]
public class aurtor: attribute // custom attributes inherit from the system. attribute
{< br> Public string name;
Public String version;
}< br> public class test // test class
{
[aurtor (name =" test event1 ", version =" 1.0.0.4 ")]
public event testhandle onhandle; // defines the delegate event onhandle
Public void testmothe3 (INT value)
{
If (onhandle! = NULL) // If the delegate event is not empty
{
Onhandle (Value + 1). tostring (); // Add 1
}
}
}
Static void main (string [] ARGs)
{
Test test = new test (); // create a class example
Type type = test. GetType (); // obtain all types of the class.
Test. onhandle + = new testhandle (testpoliconhandle); // delegate the event onhandle to trigger the event
Test. testmothe3 (1); // a parameter 1 is passed.
Eventinfo [] ETS = type. getevents (); // obtain all the events in the test class.
Foreach (eventinfo et in ETS)
{
Object [] methodattributes = ET. getcustomattributes (false); // get all attributes in the event
If (methodattributes! = NULL)
{
Foreach (Object OBJ in methodattributes)
{
If (obj is aurtor) // If the attribute is aurtor
{
Aurtor = OBJ as aurtor;
System. Console. writeline (aurtor. Name); // output custom attribute name
}
}
}
}
System. Console. Readline ();
}
}
}
Output:
2
Test event1