[To] http://blog.csdn.net/maotin/archive/2008/09/24/2972414.aspx
C #3.0 New Experience (2)
Maotin
20080924
Preface:
In addition to perseverance, learning also requires good methods! Summarizing and sorting out the materials you have learned can make the content you have learned clear and easy to find and review! As the saying goes: "A good memory is not as bad as a pen." After reading a lot of knowledge in the past, I forgot it for a while. It takes a little time, but it has little effect, however, this is a waste of time and energy caused by the absence of notes and deep learning. Therefore, every research topic should sort out the materials and conduct a series of research!
Iii. Extension Method (continued in the previous part)
The extension method is defined as follows:
Public static class extensions {
Public static void Foo (this string s ){
...
}
}
Usage:
String S = "Hello, world ";
S. Foo ();
We used to perform some processing on some parameters and objects, and write some independent methods to encapsulate these processing statements. These methods may be written in some public classes for easy reuse, for example:
Defines the number of minutes each day for a public method,
Public class publiccenter
{
// Set the input parameter to the number of days.
Public long getdaysmin (INT pdays)
{
Return pdays * 24*60;
}
}
External call:
Int days = 3;
Publiccenter pcenter = new publiccenter ();
Int minutes = pcenter. getdaysmin (days );
I think you are very familiar with the use of the above Code. In the past, there were many such cases! Now let's take a look at how to handle it with the extension method;
Defines the number of minutes each day for a static method of a static class (note that it must be static)
Public static class publiccenter
{
// Specify the number of days for the input parameter (note that this keyword is required)
Public static long getdaysmin (this int pdays)
{
Return pdays * 24*60;
}
}
External call: (Note that the static class must be in the same namespace or be referenced. You should also know this ))
Int days = 3;
// When we press "." After the int type variable, We Will intelligently prompt these self-written extension methods getdaysmin ().
Int minutes = days. getdaysmin ()
We can see that the essence of an extension method is to change the instance method call to a static method call in the static class during the compilation period.
The extension method is defined in msdn: the extension method enables you to "add" a method to an existing type without creating a new derived type, re-compiling, or modifying the original type in other ways.
Why is the extension method used?
First. easy to use: After defining an extension method of a type, just click ". ", you can find all the extension methods, instead of finding the class where the method is put, and then using the method that calls the class. (many times, public class libraries and actual calls are developed by different developers. People who need to call them often do not know which classes can be used. This is very troublesome when the public class libraries are large)
Second. convenient Extension: You can easily expand the underlying class libraries, interfaces, third-party class libraries (controls, plug-ins), and so on. Add the required functions on the top, without modifying these underlying class libraries, controls (sometimes we cannot change these items at all, such as those provided by third parties rather than open source );
Scaling methods:
1. Pass parameters:
Public static class extensions {
// This must be placed at the first position, and there is no limit on the type of parameters passed later
Public static void Foo (this string S, string pname ){
...
}
}
Usage:
String S = "Hello, world ";
S. Foo ("maotin ");
2. Priority of the extension method:
Note the priority of the extension method: the existing instance method has the highest priority, followed by the static method of the static class under the nearest namespace, and finally the static method of the static class under the distant namespace.
// Copy and modify the following content from your blog (original address:
Http://blog.joycode.com/ghj/archive/2007/06/06/103872.aspx)
Scenario 1: processing logic when the extension method is the same as the method of the original class.
Namespace hongjun. Guo
{
Public class myclass
{
Public void print ()
{
Console. writeline ("****");
}
}
Static class myextensionmethods
{
Internal static void print (this myclass S)
{
Console. writeline ("Haha" + S. tostring ());
}
}
}
Call example:
Using hongjun. Guo;
Static void main (string [] ARGs)
{
Myclass o = new myclass ();
O. Print ();
Console. Readline ();
}
What results will we see at this time ??
Answer ****
Analysis:
After the above two sets of code are compiled and decompiled into Il, we can see that the extension method does not exist on the Il layer.
The extension method is actually called by the compiler when calling a method of a class. If this method is available, it is called. If this method is not found, it is based on the referenced namespace, then find the extension method (static method of static class ). If it is found, it will be used. If it is not found, the compilation will be incorrect.
Based on the analysis results, we can understand the above problem handling results.
Case 2: Nested extension methods
For example, we have the following extension methods.
Namespace hongjun. Guo
{
Static class myextensionmethods
{
Public static int test01 (this int I)
{
Return I * 3;
}
Public static int test02 (this int I)
{
Return I + 5;
}
}
}
The following is a call example:
Static void main (string [] ARGs)
{
Int Mm = 7;
Console. writeline (Mm. test01 (). test02 ());
Console. writeline ("*****");
Console. writeline (Mm. test02 (). test01 ());
Console. writeline ("*****");
Console. writeline (myextensionmethods. test02 (myextensionmethods. test01 (MM )));
Console. Readline ();
}
Q: What is the display result of the call?
Answer: displayed in turn:, 26
Analysis:
Mm. test01 (). test02 ()
After this line of code is compiled, it is equivalent to the following code:
Myextensionmethods. test02 (myextensionmethods. test01 (mm ))
The two lines of code are exactly the same in the compiled Il.
Extension Method conflicts also need to be considered. If the same extension function (method names and parameters are the same) is defined for the same class ), calling outside will result in an ambiguous compilation problem. Therefore, you need to consider conflict when defining extension methods!
The extension method provides a good programming method. It should be introduced gradually in daily work, but there are also some restrictions. The current experience is not very deep, and new ideas will be added in the future!
The extension method is a compilation technology. Pay attention to the differences with runtime technologies such as reflection and use them with caution.