Learn and understand C # delegates

Source: Internet
Author: User

Last year's self-taught C # Tutorial is an entry-level "learning to C # 24 Lessons", the textbook also does not mention the Commission and events, the work is not how to use. Later on the Internet to read some of Daniel's blog, after reading the feeling mengmengdongdong, indefinitely, after two or three days, but completely forgotten. After all, learning this matter, wen know new, learn not to, naturally forget also quickly. For beginners like me, it's easy to understand delegates and events better. In fact, the people who have mastered, will feel that there is nothing, but not master, every time you see the Commission and events will feel very afraid. Some time ago to see the Zhangxuliang Teacher's blog about the. NET Development series PPT mentioned in a point of view, did not learn to entrust is not. Net. I was very motivated, so this time I made up my mind to learn a bit and record some of my own understanding.

A delegate, literally, means to ask someone for help to do something. After reading the article, you will find that the delegate is a pointer to a method that can be invoked through a delegate by specifying a delegate name. It's practically the same as the literal meaning.

  What is the appropriate use of a delegate

First, an example is used to illustrate the use of a delegate.

Take the student duty as an example, the duty student must do the open door, wipes the blackboard the work. The corresponding method form is as follows:

 Public void Opendoor () {    // Open Door Concrete implementation     ...}  Public void Cleanblackboard () {    // erase blackboard Specific implementation     ...}

Then write a method of duty, to complete the above work:

 Public void onduty () {    opendoor ();    Cleanblackboard ();
}

In this way, the duty of the students to open the door, clean the blackboard work is achieved. However, the scalability and flexibility of this method is not very good, assuming now on duty to increase the work, need to turn off the lights, the method is as follows:

 Public void turnofflight () {    // turn off the light's specific logic ...     }

We will need to modify the Onduty method:

 Public void onduty () {    opendoor ();    Cleanblackboard ();    Turnofflight ();}

The above code does not use a delegate, but it does the work that needs to be done. It is easy to find, open the door, clean the blackboard, turn off the lights, although their method names are different, but they have the same "form"-they do not get parameters, there is no return value (void), this is the time when the delegate can play a role. A delegate that is used to match this form. You can refer to any method of work. We can declare a delegate as follows:

Public Delegate void Dosomeworkdelegate ();

Attention:

    • When declaring a delegate, use the delegate keyword.
    • A delegate defines the "form" of a method that it can reference. You want to specify the return type (in this case, void), the delegate name (Dosomeworkdelegate), and any parameters (in this case, no arguments).

Once you have defined the delegate, you can create an instance of it and use the "+ =" operator to refer to the instance for a matching method. The code is as follows:

 Public Delegate void dosomeworkdelegate ();  Public dosomeworkdelegate dosomework;dosomework+=opendoor;

The method in the previous example is simple, with no return value and no parameters. The purpose is simply to understand the circumstances under which a delegate is used. The following is an example with parameters to illustrate how to use a delegate.

How to use delegates

Here take lectures as an example, in order to compare, also first not to use the delegate, first on the code:

 Public void Attendclass (string  name) {    //  do some extra things, such as initialization, and so on, slightly     Chineseclass ( name);}  Public void Chineseclass (string  name) {     //     ...}

The above code indicates. Attendclass Express class, when we pass on behalf of the student name name parameter, such as "Jhon", in the time, in this method, will call Chineseclass method, again pass Jhon parameters, said Jhon participated in the language class.

Assuming we have a math class now, we need to add a new method:

 public void MathClass (string  name) {    // The logic of a specific listening math lesson
}

At this time Attendclass also want to modify, before defining an enumeration as a judgment:

 public  enum   subject{Chinese,math}  public  void  Attendclass (string   name, Subject sub) { Span style= "color: #008000;" >//  do some extra things, like initialize and so on, here slightly   Swith (sub) {
    case   Subject.chinese: 
Chineseclass (n AME); break ; case Subject.Math:MathClass (name); break ; }}

OK, now the problem is solved, as the previous example said, if you want to add English class, Physical education, you have to repeatedly modify the enumeration and Attendclass. Visible program extensibility is not good.

As in the previous example, for the method of class, no matter what class, they all have the same "form", so that we can use the delegate.

Before considering how to use the delegate, let's take a look at Attendclass's method signature:

 Public void Attendclass (string name, Subject sub)

We'll just look at string name, where string is the parameter type, name is a parameter variable, and when we assign a value to a string, we can do something else with that name in the body of the method. Now if you let the Attendclass () method accept a parameter variable, This variable can represent another method, when the variable is assigned to Chineseclass, it represents the Chineseclass () method, when it is assigned to MathClass, he represents the MathClass () method. That is, let's use a parameter to substitute the method. For example, this parameter is named, subclass, and then we are in the method body, just like using subclass with parameters. Since subclass represents a method, it should be used in the same way as it is assigned (such as Chineseclass), such as

Subclass (string name)

According to this idea, attendclass () should be like this:

 Public void Attendclass (string name,*** subclass) {    subclass (name);}

Note that this position is usually placed as a type of parameter, and now there is a problem: what type of subclass parameter should be used to represent the method?

  If I say the answer is a delegate. It defines the kind of subclass method, which is the type of the subclass method parameter. As string determines the type of the first parameter of the Attendclass () method, the delegate determines the type of the second parameter in the Attendclass method.

In this example, the delegate is defined as follows:

 Public Delegate void Classdelegate (string name);

Now change the Attendclass method again:

 Public void Attendclass (string  name,classdelegate subclass) {    subclass (name);}

The delegate classdelegate appears in the same position as the string, and the string is a type, so the classdelegate should also be a type, or class. However, the delegate's declaration method and class are completely different. Then the code for the class that is complete in this example is as follows:

 Public Delegate voidClassdelegate (stringname); Public classonclass{//other Code        ...         Public voidAttendclass (stringName,classdelegate Subclass)        {Subclass (name); }                 Public voidChineseclass (stringname)        {                ...        }  Public voidMathClass (stringname) {                ...        }}

Thus, a delegate is a type. It defines the type of the method, which is actually the method as a variable. (Note the difference from the pointer)

So how do we use it, the code is as follows:

Private onclass Objonclass;objonclass=new  onclass (); string name1="xiaoming"; string name2=" Xiao Zhang "; Objonclass.attendclass (name1,chineseclass); o Bjonclass.attendclass (name2,mathclass);

The above code indicates that Xiaoming attended the Chinese class, and Xiao Zhang took part in the maths class. Since the delegate is a type. Then we can use the delegate in the following way

classdelegate delegate1,delegate2;delegate1=objonclass. chineseclass;delegate2=objonclass. MathClass; string name1="xiaoming"; string name2=" Xiao Zhang "; Objonclass.attendclass (name1,delegate1); o Bjonclass.attendclass (NAME2,DELEGATE2);

You can also pay multiple methods to the same delegate, the following code indicates that Xiao Zhang took part in the language class and took the maths class.

classdelegate delegate3;delegate3=objonclass. chineseclass;delegate3+=objonclass. MathClass; string name1=" Xiao Zhang "; Objonclass.attendclass (name1,delegate3);

As you can see, for the delegate binding method we use the overloaded + = symbol. If you change the first binding method Delegate3=chineseclass in the above code to Delegate3+=chineseclass, the error "Using unassigned local variables" will appear. We can use a delegate like this to give it initialization assignment

Classdelegate delegate3=New  classdelegate (objonclass.chineseclass); string name1="xiaoming"; Objonclass.attendclass (name1,delegate3);

We can even use the delegate without Attendclass this method, like this

Classdelegate delegate3=New  classdelegate (objonclass.chineseclass); string name1="xiaoming";d elegate3 (name1);

Therefore, you can bind multiple methods to a delegate above, and then execute them sequentially when called.

Learn and understand C # delegates

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.