C # Delegate series (I) using methods as method parameters

Source: Internet
Author: User

Delegation and events are widely used in. NET Framework. However, it is not easy for many people who have been in contact with C # for a long time to better understand delegation and events. They are like a hacker. People who have passed the hacker think it is too easy, and people who have never seen the delegate and event will feel different (BI) panic and uncomfortable. In this article, I will use two examples to describe what is delegation, why to use delegation, the origin of events, the significance of delegation and events to the observer design pattern ,. in the. NET Framework.CodeAlso discussed.

Use a method as a method parameter

Let's look at the two simplest methods, no matter how the title is spoken or whether the delegate is actually something. They are just a greeting on the screen:

Public void greetpeople (string name ){
//Perform some additional things, such as initialization.
Englishgreeting (name );
}
Public void englishgreeting (string name ){
Console. writeline ("Morning," + name );
}

For the moment, no matter whether the two methods have any practical significance. Greetpeople is used to say hello to someone. When we pass the name parameter representing someone's name, such as "Jimmy", In this method, the englishgreeting method will be called and the name parameter will be passed again, englishgreeting is used to output "Morning, Jimmy" to the screen ".

Assume thatProgramGlobalization is required. Oh, no. I am a Chinese. I don't understand what "Morning" means. What should I do? Okay, let's add a Chinese edition greeting method:

Public void chinesegreeting (string name ){
Console. writeline ("Good morning, "+ Name );
}

At this time, greetpeople also needs to be changed. Otherwise, how can we determine which version of greeting method is suitable? Before proceeding, we 'd better define another enumeration as the basis for judgment:

Public Enum language {
English, Chinese
}

Public void greetpeople (string name, language Lang ){

// perform some additional tasks, such as initialization,
swith (Lang) {
case language. english:
englishgreeting (name);
break;
case language. chinese:
chinesegreeting (name);
break;
}< BR >}

OKAlthough this solution solves the problem, it is easy to think of without saying that this solution has poor scalability. If we need to add Korean and Japanese Versions later, you have to modify the enumeration and greetpeople () methods repeatedly to meet new requirements.

Before considering a new solution, let's look at the greetpeople method signature:

Public void greetpeople (string name, language Lang)

Let's just look at the string name. Here, string is a parameter type, and name is a parameter variable. When we assign the name string "Jimmy", it represents the value of "Jimmy; when we grant it"Half smoke", It also represents"Half smoke. Then, we can perform other operations on this name in the method body. Ah, is this nonsense? I knew it when I first learned the program.

If you think about it again, if the greetpeople () method can accept a parameter variable, this variable can represent another method. When we assign englishgreeting to this variable, it represents englsihgreeting () this method. When we assign chinesegreeting to it, it also represents the chinesegreeting () method. We name this parameter variable makegreeting, so it is not the same as when we assign a value to the name. When we call the greetpeople () method, is this makegreeting parameter also assigned a value (chinesegreeting or englsihgreeting )? Then, we can use makegreeting in the method body just like using other parameters. However, because makegreeting represents a method, it should be used in the same way as the method it is assigned (such as chinesegreeting), for example:

Makegreeting (name );

Now that we have the idea, let's change the greetpeople () method. It should look like this:

Public void greetpeople (string name, *** makegreeting ){

Makegreeting (name );

}

Note that ***, this location should usually be placed in the parameter type, but so far, we just thought that there should be a parameter that can represent the method, and rewrite the greetpeople method according to this idea. Now there is a big problem:This indicates the type of the makegreeting parameter of the method?

Note:Enumeration is no longer needed here, because when assigning values to makegreeting, you dynamically decide which method to use, whether it is chinesegreeting or englishgreeting. Inside these two methods, we have already made a distinction between "Morning" and "good morning.

You should have thought about it. Now it's time to delegate the game, but let's look at the chinesegreeting () and englishgreeting () parameters that can be represented by the delegate () method signature:

Public void englishgreeting (string name)
Public void chinesegreeting (string name)

As if the name can accept "true" and "1" of the string type, but cannot accept the same true of the bool type and 1 of the int type.The parameter Type Definition of makegreeting should be able to determine the types of methods that makegreeting can represent. Further, it is the parameter type and return type of the methods that makegreeting can represent.

As a result, the delegate appears:It defines what the makegreeting parameter can representMethod TypeThat is, the type of the makegreeting parameter.

Note:If the above sentence is a detour, I will translate it into this: String defines what the name parameter can represent.Type of ValueThat is, the type of the name parameter.

Definition of delegation in this example:

Public Delegate void greetingdelegate (string name );

Can I compare it with the signature of the above englishgreeting () method? Except for the delegate keyword, are the rest identical?

Now let's change the greetpeople () method again, as shown below:

Public void greetpeople (string name, greetingdelegate makegreeting ){

Makegreeting (name );

}

As you can see, the position of the delegate greetingdelegate is the same as that of the string, and the string is a type, so greetingdelegate should also be a type or class ). However, the delegate declaration method is completely different from the class. What is this? In fact, the Delegate will indeed be compiled into classes during compilation. Because delegate is a class, delegates can be declared wherever classes can be declared. For more information, see the complete code of this example:

Using system;
Using system. Collections. Generic;
Using system. text;

Namespace delegate {
//Define the delegate, which defines the types of methods that can be represented
Public Delegate void greetingdelegate (string name );

Class program {

Private Static void englishgreeting (string name ){
Console. writeline ("Morning," + name );
}

Private Static void chinesegreeting (string name ){
Console. writeline ("Good morning, "+ Name );
}

//Note that this method acceptsGreetingdelegateType method as a parameter
Private Static void greetpeople (string name, greetingdelegate makegreeting ){
Makegreeting (name );
}

Static void main (string [] ARGs ){
Greetpeople ("Jimmy", englishgreeting );
Greetpeople ("Half smoke", Chinesegreeting );
Console. readkey ();
}
}
}

The output is as follows:
Morning, Jimmy
Good morning,Half smoke

We now make a summary of the delegation:

A delegate is a class that defines the type of a method so that the method can be passed as a parameter of another method. This way, the method is dynamically assigned to the parameter, it can avoid using the IF-else (switch) statement in a large number in the program, and make the program more scalable.

From: http://hi.baidu.com/txh1204

Delegation and events are widely used in. NET Framework. However, it is not easy for many people who have been in contact with C # for a long time to better understand delegation and events. They are like a hacker. People who have passed the hacker think it is too easy, and people who have never seen the delegate and event will feel different (BI) panic and uncomfortable. In this article, I will use two examples to describe what is delegation, why to use delegation, the origin of events, the significance of delegation and events to the observer design pattern ,. and events in the. NET Framework, and their intermediate code is also discussed.

Use a method as a method parameter

Let's look at the two simplest methods, no matter how the title is spoken or whether the delegate is actually something. They are just a greeting on the screen:

Public void greetpeople (string name ){
//Perform some additional things, such as initialization.
Englishgreeting (name );
}
Public void englishgreeting (string name ){
Console. writeline ("Morning," + name );
}

For the moment, no matter whether the two methods have any practical significance. Greetpeople is used to say hello to someone. When we pass the name parameter representing someone's name, such as "Jimmy", In this method, the englishgreeting method will be called and the name parameter will be passed again, englishgreeting is used to output "Morning, Jimmy" to the screen ".

Now let's assume that this program needs to be global. Oh, no. I am a Chinese. I don't understand what "Morning" means. What should I do? Okay, let's add a Chinese edition greeting method:

Public void chinesegreeting (string name ){
Console. writeline ("Good morning, "+ Name );
}

At this time, greetpeople also needs to be changed. Otherwise, how can we determine which version of greeting method is suitable? Before proceeding, we 'd better define another enumeration as the basis for judgment:

Public Enum language {
English, Chinese
}

Public void greetpeople (string name, language Lang ){

// perform some additional tasks, such as initialization,
swith (Lang) {
case language. english:
englishgreeting (name);
break;
case language. chinese:
chinesegreeting (name);
break;
}< BR >}

OKAlthough this solution solves the problem, it is easy to think of without saying that this solution has poor scalability. If we need to add Korean and Japanese Versions later, you have to modify the enumeration and greetpeople () methods repeatedly to meet new requirements.

Before considering a new solution, let's look at the greetpeople method signature:

Public void greetpeople (string name, language Lang)

Let's just look at the string name. Here, string is a parameter type, and name is a parameter variable. When we assign the name string "Jimmy", it represents the value of "Jimmy; when we grant it"Half smoke", It also represents"Half smoke. Then, we can perform other operations on this name in the method body. Ah, is this nonsense? I knew it when I first learned the program.

If you think about it again, if the greetpeople () method can accept a parameter variable, this variable can represent another method. When we assign englishgreeting to this variable, it represents englsihgreeting () this method. When we assign chinesegreeting to it, it also represents the chinesegreeting () method. We name this parameter variable makegreeting, so it is not the same as when we assign a value to the name. When we call the greetpeople () method, is this makegreeting parameter also assigned a value (chinesegreeting or englsihgreeting )? Then, we can use makegreeting in the method body just like using other parameters. However, because makegreeting represents a method, it should be used in the same way as the method it is assigned (such as chinesegreeting), for example:

Makegreeting (name );

Now that we have the idea, let's change the greetpeople () method. It should look like this:

Public void greetpeople (string name, *** makegreeting ){

Makegreeting (name );

}

Note that ***, this location should usually be placed in the parameter type, but so far, we just thought that there should be a parameter that can represent the method, and rewrite the greetpeople method according to this idea. Now there is a big problem:This indicates the type of the makegreeting parameter of the method?

Note:Enumeration is no longer needed here, because when assigning values to makegreeting, you dynamically decide which method to use, whether it is chinesegreeting or englishgreeting. Inside these two methods, we have already made a distinction between "Morning" and "good morning.

You should have thought about it. Now it's time to delegate the game, but let's look at the chinesegreeting () and englishgreeting () parameters that can be represented by the delegate () method signature:

Public void englishgreeting (string name)
Public void chinesegreeting (string name)

As if the name can accept "true" and "1" of the string type, but cannot accept the same true of the bool type and 1 of the int type.The parameter Type Definition of makegreeting should be able to determine the types of methods that makegreeting can represent. Further, it is the parameter type and return type of the methods that makegreeting can represent.

As a result, the delegate appears:It defines what the makegreeting parameter can representMethod TypeThat is, the type of the makegreeting parameter.

Note:If the above sentence is a detour, I will translate it into this: String defines what the name parameter can represent.Type of ValueThat is, the type of the name parameter.

Definition of delegation in this example:

Public Delegate void greetingdelegate (string name );

Can I compare it with the signature of the above englishgreeting () method? Except for the delegate keyword, are the rest identical?

Now let's change the greetpeople () method again, as shown below:

Public void greetpeople (string name, greetingdelegate makegreeting ){

Makegreeting (name );

}

As you can see, the position of the delegate greetingdelegate is the same as that of the string, and the string is a type, so greetingdelegate should also be a type or class ). However, the delegate declaration method is completely different from the class. What is this? In fact, the Delegate will indeed be compiled into classes during compilation. Because delegate is a class, delegates can be declared wherever classes can be declared. For more information, see the complete code of this example:

Using system;
Using system. Collections. Generic;
Using system. text;

Namespace delegate {
//Define the delegate, which defines the types of methods that can be represented
Public Delegate void greetingdelegate (string name );

Class program {

Private Static void englishgreeting (string name ){
Console. writeline ("Morning," + name );
}

Private Static void chinesegreeting (string name ){
Console. writeline ("Good morning, "+ Name );
}

//Note that this method acceptsGreetingdelegateType method as a parameter
Private Static void greetpeople (string name, greetingdelegate makegreeting ){
Makegreeting (name );
}

Static void main (string [] ARGs ){
Greetpeople ("Jimmy", englishgreeting );
Greetpeople ("Half smoke", Chinesegreeting );
Console. readkey ();
}
}
}

The output is as follows:
Morning, Jimmy
Good morning,Half smoke

We now make a summary of the delegation:

A delegate is a class that defines the type of a method so that the method can be passed as a parameter of another method. This way, the method is dynamically assigned to the parameter, it can avoid using the IF-else (switch) statement in a large number in the program, and make the program more scalable.

From: http://hi.baidu.com/txh1204

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.