Recently, because of a project, you need to read the data into memory and do something similar to SQL. The first thing to think about is the need to use LINQ to achieve these statistical analyses. In the process of using LINQ, we find that many of the things called extension methods help us to do some count\max\min and other functions. Functions can be implemented, but how do these extension methods work? I looked up some information and sorted out some of my thoughts in case I forgot.
According to MSDN, the extension method is presented in order to add a new "method" to the enclosing class. It is important to note that the classes here are enclosing classes, referring to classes that have no way or do not want to get the source code. What do you do to add a new function function on a class?
Method One: Use a static method and pass an instance of the class as an argument to a static method, extending the class within the method. In this way, when using the new function function, it is necessary to know the static method signature, and every time the static method is called, it is very cumbersome in the process of use, and it is not in accordance with the basic idea of human use. As follows
1 //static Method2 Private Static intStringtonum_common (stringstr)3 {4 5 Try6 {7 intnum =int. Parse (str);8 returnnum;9 }Ten Catch One { A return 0; - } - } the - //Cleint - - intnum=Stringtonum_common (str); +Console.WriteLine ("Str is {0},num is {1}", str, num);
Method Two: Use the extension method. Creates a new static class that contains the static method so that the child does not need to use a static call when using the method. As follows:
1 //Extend Class2 Internal Static classstrextend{3 Public Static intStringtonum_extend ( This stringstr)4 {5 Try6 {7 intnum =int. Parse (str);8 returnnum;9 }Ten Catch One { A return 0; - } - } the - } - - //Client + - intnum2 =Str. Stringtonum_extend (); +Console.WriteLine ("Str is {0},num2 is {1}", str, num2);
C # Extension methods