Remember the first time when using Dotween, found that the easing method can be directly used in the Transform object call to, was shocked to (that is the C # small white one). All right, come on, let's learn about this feature of C #-the extension method today.
Introduction to extension methods
Extension methods enable you to "add" methods to an existing type without creating a new derived type, recompiling, or otherwise modifying the original type.
This allows us to easily extend the object method without using inheritance, and also to add methods to the sealed class.
Let's look at an example:
1 usingSystem;2 3 namespaceStudy4 {5 class Program6 {7 Private Static voidMain (string[] args)8 {9 int[] INTs = {Ten, $, the, the, +, - };Ten varresult = INTs. (g =g); One foreach(varIinchresult) A { -System.Console.Write (i +" "); - } the - Console.read (); - } - } +}
The above code will error: The method cannot be found, because an array of type int does not have this method. If we import a LINQ package, we can use it as follows:
using System.Linq;
The reason is that it is an extension method provided by LINQ, which is a public method that we can add arbitrarily to the specified class.
Extension method Authoring
To add an extension method, we need to add a static class, as follows we add a method of extending string, through which we can get the number of words in the string.
1 usingSystem;2 3 namespaceStudy4 {5 class Program6 {7 Private Static voidMain (string[] args)8 {9 stringstr ="hi! My name is lilei!";Ten Console.WriteLine (str. WordCount ()); One A Console.read (); - } - } the - Public Static classmyextensions - { - Public Static intWordCount ( ThisString str) + { - returnStr. Split (New Char[] {' ','.','?'}, Stringsplitoptions.removeemptyentries). Length; + } A } at}
Run the program output "5".
Extension method Writing Essentials
- The extension method must be defined in a non-nested, non-generic static class;
- You must have a parameter with the This keyword, which represents a method that extends the type, passing the value of that type as a parameter;
- The first parameter cannot use an out and ref modifier;
- The first parameter cannot be a pointer type;
A null reference can also call an extension method
We all know that an empty object called by any method throws a null pointer exception, but if you use an extension method it doesn't, as follows:
1 usingSystem;2 3 namespaceStudy4 {5 class Program6 {7 Private Static voidMain (string[] args)8 {9 stringstr =NULL;Ten Console.WriteLine (str. IsNull ()); One A Console.read (); - } - } the - Public Static classmyextensions - { - Public Static BOOLIsNull ( This Objectobj) + { - returnobj = =NULL; + } A } at}
Run will return "True".
C # learning Note (eight): extension methods