In C #, the delegate and event are used to pass parameters and listen to events in WF.

Source: Internet
Author: User

Event is an important concept in Windows-based programming. In almost all Windows applications, a large number of asynchronous calls are involved, such as responding to and Clicking buttons and processing Windows system messages. These asynchronous calls must be completed through events. It is no exception even on the next-generation development platform --. NET.
So what is an event? An event is a message sent from an object. The message indicates a specific action or a specific condition. For example, the user clicks the mouse and data arrives on the socket. The object that triggers the (raise) event is called the event sender. The object that captures and responds to the event is called the event receiver ).
Here, we will discuss how to use custom events to implement our own asynchronous calls in. NET's mainstream development language C.
In C #, the implementation of events depends on delegate. Therefore, we need to first understand the concept of delegate.

Delegate

Delegate is a type in C #. It is actually a class that can hold a reference to a method. Unlike other classes, the delegate class can have a signature and can only hold references to methods that match its signature. Its functions are very similar to function pointers in C/C ++. It allows you to pass the method m of Class A to the object of Class B, so that the object of Class B can call this method m. But compared with function pointers, delegate has many advantages that function pointers do not possess. First, the function pointer can only point to static functions, while delegate can reference both static functions and non-static member functions. When referencing a non-static member function, delegate not only saves the reference to this function entry pointer, but also saves the reference to the class instance that calls this function. Second, compared with function pointers, delegate is an object-oriented, secure, and reliable managed object. That is to say, the runtime can ensure that the delegate points to a valid method. You do not need to worry that the delegate will point to an invalid or out-of-bounds address.
It is easy to implement a delegate. You can use the following three steps to implement a delegate:

1. Declare a delegate object. It should have the same parameter and return value type as the method you want to pass.
2. Create a delegate object and pass in the functions you want to pass as parameters.
3. Use the object created in the previous step to call the method where an asynchronous call is to be implemented.

The following is a simple example:
Using System;

Public class MyDelegateTest
{
// Step 1: declare the delegate object
Public delegate void MyDelegate (string name );

// This is the method we want to pass. It has the same parameter and return value type as MyDelegate.
Public static void MyDelegateFunc (string name)
{
Console. WriteLine ("Hello, {0}", name );
}

Public static void Main ()
{
// Step 2: Create a delegate object
MyDelegate md = new MyDelegate (MyDelegateTest. MyDelegateFunc );
// Step 3: Call delegate
Md ("sam1111 ");
}
}

Output result: Hello, sam1111

After learning about delegate, let's take a look at how events are handled in C.
Process events in C #
In C #, event processing is actually a delegate with a special signature, as shown below:
Public delegate void MyEventHandler (object sender, MyEventArgs e );
The two parameters, sender represents the event sender, and e is the event parameter class. The MyEventArgs class is used to contain event-related data. All event parameter classes must be derived from the System. EventArgs class. Of course, if your event does not contain parameters, you can directly use the System. EventArgs class as the parameter.
With the implementation of delegate, We can summarize the implementation of custom events into the following steps:

1. Define the delegate object type. It has two parameters. The first parameter is the event sender object, and the second parameter is the event parameter class object.
2. Define the event parameter class, which should be derived from the System. EventArgs class. This step can be omitted if the event does not contain parameters.
3. Define the event processing method. It should have the same parameter and return value type as the delegate object.
4. Define the event object with the event keyword. It is also a delegate object.
5. Add the event to the event queue with the + = Operator (the-= operator can delete the event from the queue ).
6. Call the delegate method to write the event trigger method where an event needs to be triggered. In general, this method should be a protected access restriction. It cannot be called in public mode, but can be inherited by the quilt class. The name is OnEventName.
7. Call the event trigger method to trigger the event where appropriate.

The following is a simple example:

Using System;
Public class EventTest
{
// Step 1, define the delegate object
Public delegate void MyEventHandler (object sender, System. EventArgs e );
// Skip step 2
Public class MyEventCls
{

// Step 3: Define the event processing method. It has the same parameters and return value type as the delegate object. //
Public void MyEventFunc (object sender, System. EventArgs e)
{
Console. WriteLine ("My event is OK! ");
}
}

// Step 4: Use the event keyword to define the event object
Private event MyEventHandler myevent;

Private MyEventCls myecls;

Public EventTest ()
{
Myecls = new MyEventCls ();
// Step 5: add the event to the queue with the + = Operator
This. myevent + = new MyEventHandler (myecls. MyEventFunc );
}

// Step 6: Write the event trigger function by calling delegate
Protected void OnMyEvent (System. EventArgs e)
{
If (myevent! = Null)
Myevent (this, e );
}

Public void RaiseEvent ()
{
EventArgs e = new EventArgs ();
// Step 7: trigger the event
OnMyEvent (e );
}

Public static void Main ()
{
EventTest et = new EventTest ();
Console. Write ("Please input 'A ':");
String s = Console. ReadLine ();
If (s = "")
{
Et. RaiseEvent ();
}
Else
{
Console. WriteLine ("Error ");
}
}
}

The output result is as follows:

Please input 'A':
My event is OK!

Summary
Through the above discussion, we have generally understood the concepts of delegate and event, and how to use them in C. I personally think that delegate is a very important concept in C #. If it is used properly, it can make some complicated problems very simple. Sometimes I even think that delegate can even have pointer effects, except that it cannot directly access the physical address. In addition, events are fully implemented based on delegate. Due to limited capabilities, this article only makes a Simple Discussion on the Application of delegate and event, and does not go into depth. I hope this article can serve as a reference. If you really want to have a deeper understanding of these two concepts, we recommend that you read MSDN.

Go to Dangdang to buy books at a lower price and deliver them to the door.

Related Article

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.