C ා basic knowledge series – 11 delegation and events


0. Preface

Events and delegates are high-level features of C ා, and also an interesting part of C ා. Where there is an event, there must be a delegation; however, the delegation does not necessarily have an event. So why does that happen? This needs to start from the definition of events and delegates, and understand the internal.

1. Entrustment

When it comes to delegation, I have to recall the anonymous methods introduced in LINQ, which mentioned two types: func and action. These two types are delegates.

Delegation is defined in C as an object-oriented method addressing scheme. In short, it is to define a type and then indicate that the type represents a method. The delegate object is the method parameterization. Delegation can be implemented to pass a method as a parameter to another method, or it can be considered as a special case of methodinfo in reflection (in fact, there is not much relationship).

Delegates don’t care about the name of the method, where the method comes from (which class or object it belongs to), only what parameters the method needs and what type it returns.

Here, let’s see how to define a delegation. The definition form of delegation is as follows:

Delegate < return type > delegate name (parameter list); // the parameter list represents any parameter

From the previous definition form, we can know that a delegate is also a type, so its definition also conforms to the type definition specification. Now we define a delegate with no return value or parameter type as the first delegate we create:

Public delegate void firstdel(); // type name is firstdel

Simply use the following:

FirstDel del ;
Del(); // a direct error will be reported

If the above code runs, it will directly report an error. Because you didn’t tell the compiler what the variable del should be, that is, you didn’t assign a value to del. At the same time, the delegate can be assigned a value of null, so you need to pay attention to that it can’t be null when you use it, or it can’t run.

If anonymous method is applied here, del can be assigned according to the following code:

del = ()=>
     //Ellipsis method   

Then we warm up and start to formally create a meaningful delegation:

public delegate decimal CalculateArea(decimal height, decimal weight);

The above delegation declares a specification for calculating area, using length and width for area calculation, so let’s assign it a value:

Calculatearea square = (height, weight) = > height * height; // square
Calculatearea rectangle = (height, weight) = > height * weight; // rectangle
Calculatearea triangle = (height, weight) = > height * weight / 2; // triangle

We have created three methods to calculate the area in turn, which are square, rectangle and triangle. Calling them respectively will get the corresponding calculation results:

var squrareArea = squrare(10, 10);// 100
var rectangleArea = rectangle(19, 10);//190
var triangleArea = triangle(10, 5);//25

In particular, multicast is supported by delegation in C, so it can also be used+-To register and delete. Multicast refers to multiple listeners or response methods in events and delegates. When an event triggers or delegates a call, all registered method groups will be called. When using this method to assign a value to a delegate, the delegate will be automatically converted to a method group. The simple understanding is that a list is created inside the delegate object, and then all the methods assigned to it are saved.

Therefore, the following operations will be generated:

Calculatearea calculate = square; // calculate must first assign a method
Calculate + = rectangle; // increase the area calculation method of rectangle
Calculate + = triangle; // increase the area calculation method of triangle
Calculate - = triangle; // subtract the area calculation method of triangle

Here comes a question,calculateWhat is the result of the operation, will it return an array or other types? Obviously not, because the return type defined by calculate is a decimal, no other value will be returned.

Well, this raises another question, which method’s calculation result is returned, and the calculation result of other methods? Here we tell you a result that only returns the execution result of the last registered method. Other methods execute, but the execution result of the method cannot be received by variables.

So here’s a very important practice. If you need to use a delegate as a method list, you’d better declare it asvoidOr discard the specific content of the return value.

2. Events

Event. In C ා event is like a mechanism. When a program runs to a certain stage or encounters some conditions, it will trigger an event. Then if other code subscribes to the event, the subscribed code will be executed automatically. The description is very abstract. In short, it is to declare a delegate in a class, mark that the delegate is an event, and execute the event in another method. The class that triggers this event is called the publisher, and the class that accepts or registers the handler is called the subscriber.

How do I create or declare an event? There are two ways to declare an event. One is to use it directlyEventHandler, the other is to define a delegate first, and then define events with this delegate.

1. Use EventHandler

public class EventDemo
    public event EventHandler HandlerEvent;

2. Use custom delegation

public class EventDemo
    public delegate void EventDelegate(object sender, EventArgs e);
    public event EventDelegate DelegateEvent;

The general event definition convention is commonly known as a void method. The first parameter is the sender, which indicates the event publisher. The default is the object type. The second parameter is the event variable of EventArgs type, which indicates the content that needs the attention of the subscriber when the event is triggered. It is generally used to pass some parameters.

Where EventHandler has a generic version, which is declared as follows:

public delegate void EventHandler<TEventArgs>(object sender, TEventArgs e);

The second parameter does not restrict teventargs, so we can use any type as an event variable.

Let’s take a look at what’s in EventArgs. There’s only one default constructor and several methods inherited from object. So in development, we will define an event variable type ourselves, and inherit EventArgs for consistency.

C ා it is suggested that the definition of the event starts with on, indicating when it is triggered. The example code does not conform to this specification.

3. Use the following events and delegates

Create a class with events:

public class EventDemo
    public delegate void EventDelegate(object sender, EventArgs e);

    public event EventDelegate DelegateEvent;

    public void Trigger()
        If (delegateevent! = null) // trigger the event, and judge whether the subscriber list of the event is empty on demand
            DelegateEvent(this, new EventArgs());

Use the following:

EventDemo demo = new EventDemo(); 
demo.DelegateEvent += (sender, eventArgs) =>
    //Omit subscriber's method content
demo.Trigger (); // trigger event

When the publisher tries to trigger the event, the subscriber receives the message, and then the register subscriber method is called. The publisher passes a pair of sender and EventArgs to the subscriber, and the subscriber processes them according to his own logic.

It is obvious that the event handler registration method uses the+=, so there is also a-=Indicates unsubscribe.

So far, the basic concepts of delegation and event have been introduced. Of course, it’s still that sentence, and more content is in practice. C ා s event mechanism gives programmers more freedom to customize events, rather than being limited to certain frameworks. So you can try more C Chen events, maybe you can find more content I don’t know.

Please pay more attention to my blog “Mr. Gao’s cabin”

C ා basic knowledge series - 11 delegation and events

Recommended Today

The way of nonlinear optimization

Mathematical knowledge 1、 Nonlinear functionLinear function is another name of a function of first degree, then nonlinear function means that the function image is not a function of a straight line.Nonlinear functions include exponential function, power function, logarithmic function, polynomial function and so on. 2、 Taylor expansion1. Taylor formula:Taylor’s formula is to add a_ The […]