19. Extensions
For example, if you want to add a new method to a class, but for some reason, you cannot directly modify the source code of the class. You can implement the method by extending the class.
An example is as follows:
Suppose there is a class show
1 public class show 2 {3 Public void methodone () 4 {5 console. writeline ("methodone"); 6} 7} 8 9 // extended class 10 public static class showextension11 {12 public static void methodtwo (this show s) // The first parameter is the type to be extended. After the keyword this, the compiler will know that this method is part of the show type. 13 {14 console. writeline ("methodtwo"); 15} 16} 17 18 19 class program20 {21 static void main () 22 {23 show s = new show (); 24 s. methodone (); 25 s. methodtwo (); // when calling the method of the extension class, the first parameter does not need to be processed. Although the extension method is static, it must be called using the standard instance method syntax. 26 console. Read (); 27} 28}
Note: If the extension method has the same name as a method in the class, the extension method is not called. Any existing instance methods in the class are preferred.
20,
C # easily overlooked knowledge points (4)