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.