Extension Method, c # Extension Method
The extension method enables you to "add" methods to existing types without creating a new derived type, re-compiling, or modifying the original type in other ways. An extension method is a special static method, but it can be called like an instance method of an extension type. (Derived from csdn)
It may be better understood with an example
Extension Method:
Public static class Helper {public static bool IsNullOrEmpty (this string str) {return string. IsNullOrEmpty (str );}}View Code
Usage:
Static void Main (string [] args) {Console. Write ("qwe". IsNullOrEmpty (); Console. ReadKey ();}View Code
The extension method must be static class or static method. Why is it static? You can see the source code.
The extension method is actually a static method call.
Bytes ---------------------------------------------------------------------------------------------------------------------------
When an instance object has a method with the same name as the extension method, what method will it perform?
Public static class Helper {public static void Miao () {Console. writeLine ("I am the kitten of the Extension Method");} public class Cat {public void Miao () {Console. writeLine ("I Am a kitten from an instance ");}}View Code static void Main (string [] args) {Cat c = new Cat (); c. Miao (); Console. ReadKey ();}View Code
It can be seen that the compiler will give priority to finding the Miao method in the Cat class during compilation. If the Miao method is found, the execution method will be executed. If the method is not found, the extension method will be searched and executed.