Instances that combine custom attributes and event Delegation

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.