In the previous article, we will talk about the extension method. Here we will talk about the usage in the previous article.
Extension methods can help us add methods to existing types to meet our needs. For example, we can use the extension method to add an IsValidEmailAddress Method to the string class to check whether it meets the Email standard.
1. Define extension methods
The extension method specifies that the class must be static. All methods contained in the class must be static ,(Note:: Extension attributes and events cannot be defined. The first parameter specifies the type of the action of the method and uses this as the prefix.
For example
public static classMyExtensions { public static int WordCount(this Stringstr) { return str.Split(new char[] { ' ','.', '?' }, StringSplitOptions.RemoveEmptyEntries).Length; } }
The parameter of this method uses this to indicate that it is modified to the this type,
2. Use
The extension method is defined as a static method, but can only be called through the instance, and the parameter is prefixed with this. it is also bound during compilation. before using it, first introduce the namespace and then instantiate the object to call it.
3. Use instances
There are many methods for the String class, but some of them are not quite used to it. Here we write an exception prompt class with null characters. It is mostly used for passing the check.
The static class is preferred.
Using System; usingSystem. collections. generic; using System. linq; using System. web; usingSystem. diagnostics; usingSystem. reflection; using System. IO; namespace ConfigurationSectionTest1 {public static class ThrowError {// DebuggerNonUserCode. if the types and members provided by the designer are not part of the Code specifically created by the user, the complexity of the debugging process is increased. This feature disables the display of these affiliated types and members in the debugger window and automatically passes through the statements without entering and executing the Code provided by the designer in a single step. When you pass the user code one by one, if the debugger encounters this feature, the user will not see the Code provided by the designer, and will execute the next code statement provided by the user. /// <Summary> /// check whether the object is empty. If it is empty, throw an exception /// </summary> /// <typeparam name = "T"> </typeparam> /// <param name = "data"> </param>/ // <param name = "message"> </param> // <param name = "messageParams"> </param> [DebuggerNonUserCode] publicstatic void NullCheck <T> (this object data, string message, paramsobject [] messageParams) where T: System. exception {(data = null ). trueThrow <T> (message, messageParams);} // <summary> // check whether the object is empty. If it is empty, throw ArgumentNullException /// </summary> /// <param name = "data"> parameter of the object to be checked </param> /// <paramname = "message"> name </param> [DebuggerNonUserCode] publicstatic void NullCheck (this object data, string message) {NullCheck <ArgumentNullException> (data, message) ;}/// <summary> /// if the result value of the condition expression boolExpression is true (true ), throw the error message specified by strMessage /// </summary> /// <paramname = "parseExpressionResult"> condition expression </param> /// <paramname = "message"> error message </param> /// <paramname = "messageParams"> parameter of the error message </param> /// <typeparam name = "T"> exception type </ typeparam> /// <remarks> // if the result value of the conditional expression boolExpression is true ), the error message [DebuggerNonUserCode] publicstatic void TrueThrow <T> (this bool parseExpressionResult, string message, params object [] messageParams) where T: System. exception {if (parseExpressionResult) {if (message = null) throw new ArgumentNullException ("message"); Type exceptionType = typeof (T); Objectobj = Activator. createInstance (exceptionType); Type [] types = new Type [1]; types [0] = typeof (string); ConstructorInfo constructorInfoObj = exceptionType. getConstructor (BindingFlags. instance | BindingFlags. public, null, CallingConventions. hasThis, types, null); Object [] args = new Object [1]; args [0] = string. format (message, messageParams); constructorInfoObj. invoke (obj, args); throw (Exception) obj ;}}}}
For the caller, it is often used for parameter detection of the method.
Pubilc void test (string Id) {Id. NullCheck ("the character Id cannot be blank ");}Legend
The instantiated Id can directly call this method for judgment. If it is null, a prompt is thrown.
Summary:
The above is an extension of the string type. Of course, other types can also be extended to create methods that meet your own needs. The Extension Method associates with our static method. The static method does not target a certain type, but the extension method does not inherit from a certain type of extension. This is their difference.