Introduction to subscribe to events through delegate

Source: Internet
Author: User
Delegation and events are a new term in the C # language. They actually originated from function pointers in c/C ++.

Steps:
1. Declare a delegate object.
2. Implement a function with the same parameters and return values as delegate (which can be static or non-static ).
3. When a delegate object is generated, pass the function you just implemented as a parameter to its constructor.

Let's take a look at the following example:
In the DAL class:

Public delegate void deleException (System. Exception exception); // declare a delegate
Public event deleException evenException; // defines a delegate type event
Public void CallEvent (System. Exception exception) // trigger event Method
{
DeleException messageEvent = evenException;
If (messageEvent! = Null)
{
// Notify all subscribed events (send messages)
MessageEvent (exception );
}
}

/// <Summary>
/// Open the connection to the database
/// </Summary>
/// <Returns> </returns>
Public bool Open ()
{
Try
{
If (m_SqlCeConnection! = Null & m_SqlCeConnection.State = ConnectionState. Closed)
M_SqlCeConnection.Open ();
Return true;
}
Catch (System. Exception e)
{
CallEvent (e); // trigger the event
Return false;
}
}

In Form1:
Private void ShowMessage (Exception ex) // event processing
{
MessageBox. Show (ex. Message );
}

DAL _ dal = new DAL (......)......;
_ Dal. evenException + = new deleException (ShowMessage); // listens for events
_ Dal. Open (); // if an exception occurs during Open (), ShowMessage () is called ();

In the above example, we may not see any good information, but in some cases, it is very important. For example, updating the UI through a thread is not safe because the thread directly updates the UI.
"Delegate" is a "function pointer" linked list. Of course, this linked list can have only one element. If so, "delegate" is equal to "function pointer ";
"Event" is a special type of "delegate". You define an "Event", indicating that you have defined both a delegate and two methods.
 

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.