C # extension method,
There is no such thing in java. Once a class is final, this class can no longer be added to the method, but C # can do this, you can add a new method to the sealed class, I prefer c.
This is the extension method in C.
So under what circumstances do we need to write extension methods for a class?
The following are three elements of the Extension Method: (it is also a syntax rule)
Here is a chestnut:
We generally Convert a number of the string type to the int type. Generally, we use the int. Parse () method or the Convert method. Can we add a Parse Method to the string type?
Yes, of course. The Code goes up first: (here, only the extension method without parameters is written. If there are parameters, you can directly add them to the parameter list. During the call, the corresponding parameters are passed)
using System;namespace ConsoleApplicationTest{ public static class stringExtensionMethod { public static int Parse(this string str) { return int.Parse(str); } } class Program { static void Main(string[] args) { string str = "111"; int i = str.Parse(); Console.WriteLine("i: " + i); } }}
It may be hard to understand why there are parameters in the parameter list, but no parameters are passed during the call. I was a bit confused about this, but I just figured it out, isn't there a this keyword? This refers to the current object, that is, the instance of the extended class, that is, the caller of the extension method. Since it is the caller, it must be transmitted as a parameter.
The following describes the features of the extension method: