Extension methods use

Source: Internet
Author: User
Tags throw exception types of extensions

The previous article said that the extension method of the simple introduction, here is the continuation of the next chapter on the use of methods.

extension methods can help us to add methods to existing types . To meet our needs. For example , We can use an extension method to Add a isvalidemailaddress method to the string class to detect conformance to Email Standard .


1 Defining extension methods

The extension method specifies that the class must be static . all the methods included in it must be static. , ( note : You cannot define extended properties and Events ). and The first parameter specifies the type of method action,with Thisfix the prefix..

Like what

public static classmyextensions    {public        static int WordCount (this stringstr)        {            return str. Split (new char[] {", '. ', '? '},                            stringsplitoptions.removeemptyentries). Length;        }    }  

the parameters of this method are used This , indicates that the change itself is This type ,

2 Use

extension methods are defined as static methods , but through the instance talent call , and the number of references to This Change to prefix . and is bound at compile time. . introduce namespaces first before use , the object is then instantiated to be called.


3 usage Examples

There are many methods of String classes , But some are not very accustomed to it . here is a null-character exception hint class. . more for pass-through checking

preferred definition Static class . when you define a static method

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. Assume that the types and members provided by the designer are not part of the code that is specifically created by the user. The complexity of the debugging process is added. This attribute disables the display of these subordinate types and members in the debugger form and voluntarily steps through without stepping into the code provided by the designer. When stepping through user code, assume that the debugger encounters this attribute. The user will not see the code provided by the designer. The next code statement provided by the user is also run. <summary>///checks if the object is empty. assumed to be empty. Throw 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>///checks if the object is empty. Assuming null, throw argumentnullexception///</summary>///<param name= "Data" > Checked object </param>///<paramname = "MesSage "> Parameter name </param>[debuggernonusercode]publicstatic void Nullcheck (This object data, string message) { Nullcheck<argumentnullexception> (Data,message); }///<summary>///assumes that the result value of the conditional expression Boolexpression is true (true). Throws the strmessage specified error message///</summary>///<paramname= "Parseexpressionresult" > Conditional expression </param>///< Paramname= "message" > Error message </param>///<paramname= "Messageparams" > Error message in </param>///< Typeparam name= "T" > Exception type </typeparam>///<remarks>///assuming that the result value of the conditional expression Boolexpression is true (true), The error message specified by the message is thrown [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 tune-in method party , often used on the method 's parameter detection

PUBILC void Test (string id) {Id.nullcheck ("character ID cannot be null");}
legend

The instantiated Id can call the method directly, infer, and empty, then throw the hint we wrote.


Summary:

these are the string types of extensions. Of course, other types can be expanded to create the way that suits their needs. The static method that the extension method associates with us. Static mode is not for a certain type. But the extension method is this extension to a certain type, without inheritance.

This is their difference.


Extension methods use

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.