As the name implies, this is an operation that can extend the C # class, as the MSDN statement says:
The extension method enables you to add a method to an existing type without creating a new derived type, recompiling, or otherwise modifying the original type. ”
is usually used to extend the classes that we can't modify, such as
String,int,datarow,datatable these.
For example, a string type has a method called Contains, which can be used to test whether a specified string or character is contained in the strings.
Now I need to determine if there are no strings in the string I've drawn up. What to do, I wrote a Nocontains method, if the string does not contain an array of strings in the argument, it returns to true, and then as an extension method loaded into the string type.
The code is as follows:
This allows you to use the Nocontains method of the string directly.
Examples of use are as follows:
Array is a string array, and you can extend the method of the string class as long as you define such a static class in your project.
With regard to the definition of extension methods, the idea on MSDN is:
Extension methods are defined as static methods, but they are called through the instance method syntax. Their first argument specifies which type the method acts on, and the parameter is prefixed with the This modifier.
Specifically, the extension method must be placed in a static class, the extension method itself must be a static method, and then the first parameter of the extension method must be the type you want to extend, and precede the This modifier.
PS: It is not easy to express in concise words, read more books to improve the ability to express.
Blog Original address: http://blog.deali.cn/?p=832
My public number: Dealiaxy
Introduction to C # extension methods