C # Delegate and Event

zhaozj2021-02-17  106

In a Windows platform-based programming, events (event) is a very important concept. Because in almost all Windows applications, a large number of asynchronous calls, such as responding to clicking buttons, processing Windows system messages, etc., these asynchronous calls need to be done by events. Even in the next generation development platform --.NET is no exception.

So what is an event? The so-called event is a message issued by an object. This message marks a particular behavior that occurs, or a particular condition is established. For example, the user clicks the mouse, there is data arrival on the socket. That trigger (RAISE) event is called an event's sender (Event Sender), capturing and responding to an event of an event called event receiver.

Here, we will discuss how our own asynchronous calls are implemented in the mainstream development language C # of .NET.

In C #, the implementation of the event relies on Delegate, so we must first understand the concept of delegate.

Delegate

Delegate is a type in C #, which is actually a class that can hold a reference to a method. Unlike other classes, the Delegate class can have a signature, and it can only hold a reference to the method that matches its signature. Its implementation is very similar to the function pointers in C / C . It allows you to pass a class A method m to the object of another class B, so that the object of class B can call this method M. But than the function pointer, Delegate has many functions that have many function pointers. First, the function pointer can only point to the static function, and DELEGATE can reference the static function and can reference the non-statistial member function. When references the non-static member function, DELEGATE not only saves references to this function portal pointer, but also saves references to class instances that call this function. Second, DELEGATE is an object-oriented object-oriented, type, secure, and reliable control (Managed). That is, Runtime ensures that delegate points to an effective way, you don't have to worry that Delegate will point to invalid addend or base address.

Implementing a delegate is very simple, you can implement a delegate by the following three steps:

1. Declare a Delegate object that should have the same parameters and return value types as you want to pass.

2. Create a Delegate object and incorporate the function you want to pass as a parameter.

3. Call the method by the object to be created in the previous step.

Here is a simple example:

Using system;

Public Class MyDelegateTestSt

{

// Step 1, declare the delegate object

Public delegate void mydelegate (String name);

// This is the way we want to pass, it has the same parameters and return value types with 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 DelegateMD ("SAM1111");

}

}

The output result is: Hello, SAM1111

Learn Delegate, let's take a look at how the event is handled in C #.

Processing in C #

Event processing in C # is actually a delegate with a special signature, like the following:

Public Delegate Void MyEventHandler (Object Sender, MyEventArgs E);

Two of these parameters, Sender represents event senders, E is an event parameter class. MyEventargs class is used to include data related to events, and all event parameter classes must be derived from the System.Eventargs class. Of course, if your event does not include parameters, you can use the System.EventArgs class as a parameter.

It is such a simple, combined with Delegate implementation, we can break the implementation of custom events to the following steps:

1. Define the delegate object type, it has two parameters, the first parameter is an event sender object, the second parameter is an event parameter class object.

2. Define event parameter classes, which should be derived from the System.Eventargs class. This step can be omitted if the event does not have a parameter.

3. Defining an event handling method, it should have the same parameter and return value type with the Delegate object.

4. Define an event object with an Event keyword, which is also a delegate object.

5. Add events to the event queue with = operator (- = operator) to remove events from the queue).

6. Write an event trigger method in a way that is required to trigger events. In general, this method should be protected by protected, which cannot be called in public mode, but can be inherited by subclasses. The name is oneventname.

7. Call the event trigger method to trigger the event at the appropriate place.

Here is a simple example:

Using system;

Public Class Eventtest

{

// Step 1, define the delegate object

Public Delegate Void MyEventHandler (Object Sender, System.EventArgs E);

// Step 2 omit

Public Class MyEventCls

{

// Step 3, define an event processing method, which has the same parameter and return value class // type with the Delegate object

Public void MyEventFunc (Object Sender, System.EventArgs E)

{

Console.WriteLine ("My Event IS OK!");

}

}

// Step 4, define an event object with an Event keyword

PRIVATE EVENT MyEventHandler MyEvent;

Private myeventcls myecls;

Public EVENTTEST ()

{

MyEcls = new myeventcls ();

// Step 5, add the event to the queue with = operator

This.Myevent = new myeventhandler (myecls.myeventfunc);

}

// Step 6 to write an event trigger function to call Delegate?

Protected void onmyevent (system.eventargs e) {

IF (MyEvent! = NULL)

MyEvent (this, e);

}

Public void raiseevent ()

{

Eventargs e = new eventargs ();

// Step 7, trigger events

OnMyEvent (E);

}

Public static void

Main

()

{

Eventtest et = new eventtest ();

Console.write ("Please Input 'A':");

String s = console.readline ();

IF (s == "a")

{

et.raiseevent ();

}

Else

{

Console.writeline ("Error");

}

}

}

The output is as follows, the black body is the user's input:

Please Input 'A': a

My Event IS OK!

summary

Through the discussion above, we generally understand the concept of Delegate and Event, and how to use them in C #. I personally think that DELEGATE is a fairly important concept in C #, whimsably uses it, makes some quite complex problems very simple. Sometimes I even think that Delegate can even have a pointer, in addition to can't access physical addresses directly. Moreover, the event is also fully implemented based on delegate. Due to the limited capacity, this article is only a light discussion for Delegate and Event, and I hope that this article can play the role of throwing jade. I really want to have more deep understanding of these two concepts, or recommend everyone to see MSDN.

转载请注明原文地址:https://www.9cbs.com/read-31521.html

New Post(0)