I remember when I was just learning to program, the teacher often mentioned a word: Notice the null pointer. So often in some "entry" position, code validation, null pointer judgment is one of the work.
The string type, as a common data type, has a very high probability of appearing in a project, so there are often the following code snippets:
STR is a String type if (str = = NULL | | str = = string. Empty) { //... Other operations return; }
Write two double equals sign each time to judge, really a bit annoying, make people distressed unceasingly. In the following period of time, I was fortunate to find a new way of writing:
STR is a String type if (string. IsNullOrEmpty (str)) { //... Other operations return; }
But there are some places to judge whether it is a space ...
STR is a String type if (String.IsNullOrEmpty (str) | | | str. Trim (). Length = = 0) { //... Other operations return; }
The code length is getting longer ... Wait, don't worry,. NET 4.0来 ...
STR is a String type if (String.isnullorwhitespace (str)) { //... Other operations return; }
This method is very powerful, not only can judge the space, but also can judge the tab ' \ T ' and other white space characters.
But... But... I still feel uncomfortable, if I can achieve the following effect is much better.
string str = null; BOOL result = str. IsEmpty (); Console.WriteLine (result); Normal compilation passes, normal operation does not occur exception, and output True
Let's say I have some means to make a string object have a IsEmpty method:
If IsEmpty is an instantiation method, the Str object is null, and the calling method must throw a null pointer exception.
If IsEmpty is a static method, the object cannot invoke a static method according to the syntax rules.
So, this road does not seem to be feasible, how to do? --Let the extension approach solve it.
C # Programming Guide-extension methods, instructions: extension methods enable you to "add" methods to existing types without creating new derived types, recompiling, or otherwise modifying the original types.
An extension method is a special static method, but it can be called just like an instance method on an extended type.
It seems that the extension method is very powerful, so how do we implement and invoke the custom extension method?
1, because the extension method is to "add" to the existing type method, there must be a type, here is the type of string we want to add a method.
2, the extension method is also the method, the method always needs "carrier", so we need a class. There are only two points required for this class:
1) is the top-level static class, 2) is sufficient access to the customer code.
3, the requirements for the extension method has four points, in addition to static methods and for the customer code has sufficient access, also requires: 1) The first parameter of the extension method must be the type to be extended,
This is the string type. 2) there and only the first parameter must begin with the this modifier.
4, write the extension method, introduce the appropriate namespace (if necessary), based on the intelligent sensitivity of VS, and then write code calls.
Demo:
Using system;using system.collections.generic;using system.linq;using system.text;using System.Threading.Tasks; namespace methoddemo{public static class Stringextentsion {public static bool IsEmpty (this string str) { return string. Isnullorwhitespace (str); } } Class program { static void Main (string[] args) { string[] arr = new string[] {null, string. Empty, "", " \ t ", " \ r \ n "}; foreach (String str in arr) { bool result = str. IsEmpty (); Console.WriteLine (result); Compile pass, run no exception, and all output true } console.read (); } }
Let's take a closer look at this demo, Wow, the object can be called static method, which completely broke the previous grammatical rules ah. Is that right? Let us be suspicious of the state of mind to explore.
We used the VS self-brought Il disassembler to decompile and look at the MSIL code. The IsEmpty method signature for the Stringextentsion class is as follows:
. method public Hidebysig static bool
We can find the familiar shadow public static bool IsEmpty (String str) {}, which is the same as a standard static method, the This modifier has "disappeared" at this time.
Look at the customer code again:
il_003b: Call bool Methoddemo.stringextentsion::isempty (String)
Even if you don't understand the MSIL code, I think you might have guessed the correct result--yes, we were "tricked" by the compiler, the following two formulations are equivalent:
result = Str. IsEmpty (); result = Stringextentsion.isempty (str); The This modifier in the extension method is optional
See here, there is a general understanding of the extension method, and we look back at the C # Programming Guide-the extension method, a description of the sentence:
extension methods enable you to "add" methods to existing types, Without creating a new derived type, recompiling, or otherwise modifying the original type. extension methods are a special kind of static method,
But it can be called just like an instance method on an extended type.
1, here "add" two words are added double quotation marks, so the name is not really add, extension method also exists in its definition of static class, compiled method signature and standard static method no difference,
This modifier, which has disappeared at this time.
2, the extension method is a special static method, which is special in its syntax rules to ensure that the compiler can "extend the object call static method (extension method) This syntax representation" compiled through.
As you can imagine, when the compiler compiles, it looks for all extension methods under the namespaces introduced by the current code file domain, and its workload is significant (see also: ExtensionAttribute).
Postscript:
1, this example is very special, can show the absolute power of the extension method:
1) string is a class in a. NET class Library, we cannot modify the string class.
2) string is a sealed class and cannot be inherited.
3) To avoid null pointer exceptions, the most convenient way to do this is by using the parameters of the static method, like string. Isnullorwhitespace method,
But the desired form is the object invocation instance method.
2. What happens if you add an extension method to object? (not to be continued ...)
. NET extension Methods (i)