Due to the business requirements, the system may not be able to provide a method to help us to complete the corresponding functions,
You can extend the method of the system class at this point.
The extension method is essentially a static method, except that C # provides convenience, and the extension cannot call the private, protected members of the extended class internally.
It can also be seen in the following code that the static class Myextend is used for extending the string class method.
There are three steps to write an extension method:
1. Declare that a class is static, and here it also adds the access modifier for the class public, so that it can be called.
2. Declaring a static method
3. The notation of the parameter, the format of this extension class name parameter Parameters 1 formal parameter 2 ...
Where the this extension class name parameter is fixed, the following parameters are optional, the next is the actual call to the extension method is required to pass the parameter.
Code parsing:
1. Label the static class public static classes myextendclass { //2. static method //3. This is required to decorate the type followed by the extended type followed by the real argument public static int GetCount (this string msg,int s) { return MSG. Length+s;}}}
Call
You can see that this method has been marked as an extension method. The parameters are also consistent as described above.
C # Extension methods