How to define and invoke extension methods

Source: Internet
Author: User

From MSDN: the best. NET Learning Library https://msdn.microsoft.com/zh-cn/library/gg145045%28v=vs.110%29.aspx

Extension methods enable you to "add" methods to an existing type without creating a new derived type, recompiling, or otherwise modifying the original type.

  An extension method is a special static method, but it can be called just like an instance method on an extended type.

this modifier. " > Their first parameter specifies which type the method acts on, and the parameter is prefixed with the This modifier.

this modifier. " > system. The String class. The following example shows an extension method defined for the System.String class. Note that it is defined internally in a non-nested, non-generic static class: for example:

  

      Public Static classMyExtensions { Public Static intWordCount ( ThisString str) {            returnStr. Split (New Char[] {' ','.','?'}, Stringsplitoptions.removeemptyentries).        Length; }    }   

You can use this using directive to place the WordCount extension method in scope:

using Extensionmethods;

Also, you can invoke the extension method from the application using the following syntax:

string " Hello Extension Methods " ; int i = S.wordcount ();//Results: 21

In code, you can call the extension method using the instance method syntax. However, the compiler-generated intermediate language (IL) translates the code into a call to a static method. Therefore, the encapsulation principle is not really violated. In fact, extension methods cannot access private variables in the types they extend.

How to define and invoke extension methods

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.