C # Extension methods

Source: Internet
Author: User

Due to the business requirements, the system may not be able to provide a method to help us to complete the corresponding functions,

You can extend the method of the system class at this point.

The extension method is essentially a static method, except that C # provides convenience, and the extension cannot call the private, protected members of the extended class internally.

It can also be seen in the following code that the static class Myextend is used for extending the string class method.

There are three steps to write an extension method:

1. Declare that a class is static, and here it also adds the access modifier for the class public, so that it can be called.

2. Declaring a static method

3. The notation of the parameter, the format of this extension class name parameter Parameters 1 formal parameter 2 ...

Where the this extension class name parameter is fixed, the following parameters are optional, the next is the actual call to the extension method is required to pass the parameter.

Code parsing:

    1. Label the static class public static classes  myextendclass    {        //2. static method         //3. This is required to decorate the type followed by the extended type followed by the real argument        public static int GetCount (this string msg,int s)        {            return MSG. Length+s;}}}    

Call

You can see that this method has been marked as an extension method. The parameters are also consistent as described above.

C # 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.