"C #" delegate and event

Source: Internet
Author: User

Before you begin, talk about the habit of expressing your article first.

New Object ();

In the above example, object is a type, a is a reference, new object constructs an object, and sometimes "construct object" is also called "create instance". Some articles are used to refer to a also as instances, please do not confuse according to context understanding. Next you will often see expressions such as "object Type", "Object" referencing "Object Objects".

In addition, I will try to use "method" instead of "function" salutation. Readers who are accustomed to C + + should not be confused when they see the "method" next.

Delegate Introduction

Delegate's Chinese meaning is a delegate, and in C # is also a key word. In the System namespace, there are Delegate classes and MulticastDelegate classes, which inherit the former. Compilers and other tools can derive from MulticastDelegate, but we cannot explicitly inherit these two classes. In order to use delegate, we need to use the delegate keyword to declare a delegate type:

int mydelegate (int arg);

As with other types, this declaration can be placed inside a namespace or within other classes. We just have to write this line of code, and the compiler implements the details for us. Note the section after the delegate keyword can be any reasonable method signature (the method signature consists of the method's parameter list and the return value, both of which have the same signature).

Now that we have declared a delegate type MyDelegate, we will then create an instance with this type:

New MyDelegate (Method);

It does not make much difference to create an instance of another class, but what is the constructor's parameter Method? Method must be a name that is consistent with the signature of the MyDelegate declaration, which means that the signature of method must contain an int parameter and an int return value (this is not accurately described, due to C # covariance and contravariance characteristics, detailed reference: Covariance and Contravariance in a delegate). Delegate is a reference type, so if the reference instance is not initialized for sample, then the value of sample is null.

Now there is a problem. If method is static, then it is not a problem to pass the parameter, and if method is not static, it is not necessarily correct. We know that ordinary methods must be invoked by specific objects, so it makes no sense to pass an ordinary method to the constructor of delegate without specifying the owning object. If the above code is in the normal method of the class, because the This keyword can be omitted, the Method is understood by the compiler as this. method, which belongs to the object is clear, so is still correct, if the above code in the static method of the class, then because the method does not have a specific object and error. This detail needs to be noted.

Finally, we need to know how to invoke the method stored in the delegate instance.

int a = sample (3);

It looks no different than calling Method directly. This is true, just be aware that the delegate reference, if NULL, causes a null reference exception. Delegate references, like other types of references, can also perform = assignment operations, pass arguments as methods, and use point operators. Access to object members.

So far, you might think that delegate is similar to a function pointer in C + +. However, the delegate type can also perform +/+= and-/-= operations because the delegate object does not just save a reference to a method, but instead saves a list of methods.

Sample-= Method;sample + = Method;

-Used to remove a method from the method list, + to add a method. The + operation does not exclude the exact same method reference. Now, the meaning of sample (3) is to call each method in the method list in turn, and the return value of the last method as the return value of sample (3).

Note the type conversion issue. In the above code, we add the method to the delegate. In fact, you can also directly assign the method to the delegate reference. These practices are justified because the methods can be implicitly converted to delegate.

To simplify programming, a series of generic delegate are pre-declared in the System namespace. With these statements we almost no longer need to do additional declarative work.

PublicDelegatevoidAction ();PublicDelegatevoid action<t> (T arg); delegate void action<t1, T2> (T1 arg1, T2 arg2); // There are more parameter versions of Actiondelegate TResult func<tresult> (); public delegate TResult func<t, Tresult> (T Arg); public delegate TResult func<t1, T2, tresult>< Span style= "color: #000000;" > (T1 arg1, T2 arg2); // There are more parameter versions of Func       

Anonymous methods and Lambda expressions

In the above, we must declare the method methods in advance to initialize the delegate instance. C # provides anonymous methods to simplify the initialization of delegate.

Delegate (int arg) {    return arg * arg;};   

It looks as if a new method is declared inside the running code and saved with sample. Doing so makes the code more concise. Note The return type of the anonymous method, which must be or can be implicitly converted to the delegate declaration when the signature is returned. Another benefit of anonymous methods is that you can access external variables, and the anonymous method captures references to external variables instead of values, which you need to be aware of, see this code:

0Delegate (return n *1;p rint (sample (1));    

The result is Output 1 instead of 0. In addition anonymous methods cannot access external ref or out parameters.

A LAMBDA expression is an anonymous function. Specify an input parameter on the left side of the lambda operator =, and the execution expression or statement on the right.

Sample = x = x * x;

Looks very similar to the anonymous method above. Virtually all of the limitations and characteristics of an anonymous method apply in a lambda expression.

Let's look at the input parameters section of the LAMBDA expression:

no parameter Use () () = dosomething ();  A parameter directly writes out the parameter name arg = arg * arg;  multiple parameters used, split (arg1, arg2) = Arg1 = = arg2;  parameter types cannot be inferred when you can explicitly specify (char arg2) = = Arg1. Split (arg2);          

In these examples, the right side of,=> is a single expression, and if you need to return a value, the value of the expression is the return value. You can write multiple statements using curly braces, but you must explicitly specify the return value using return.

(arg1, arg2) ={    0;    1:-1;}     

About Event

Event Chinese means events, which is also a keyword in C #. Here's how the event is declared:

Event mydelegate myevent{    Add {print ("" + value);} Remove {print ("" + value);}}      

Looks similar to a property declaration. The event has two operations: + = and-=, and the right operand must be delegate (or null) that is consistent with the event type. + = calls the add,-= call is remove. The following is an example of a call:

NULLnull;

The result prints "add:" and "Remove:".

There is a simpler way to declare it:

Event MyDelegate MyEvent;

This declaration is similar to (actually not the same):

Private mydelegate _myevent;  Event mydelegate myevent{    Add {_myevent + = value;} remove {_myevent-= value;}}    

Using this simple declarative method, you can manipulate the event in the same class as the myevent, including the = assignment operation and the calling method, but elsewhere, you can only use the + = and-= operations. The purpose of this is to encapsulate all potentially unsafe operations inside the class. Yes, that's it, no more.

Finally, the purpose of the article is to describe the delegates and events in a simple language as much as possible, thus ignoring all the relevant details such as asynchronous operations. For more detailed information, please refer to MSDN or this article: C # in Depth:delegates and Events.

"C #" delegate and event

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.