[C #] Extension Method

Source: Internet
Author: User

Frontier:

The extension method enables you to "add" methods to an existing type without creating a new derived type, re-compiling, or modifying the original type in other ways. An extension method is a special static method, but it can be called like an instance method of an extension type.

Body:

To understand the extension method, the best way is to look at the code. Suppose we want to define the following indexof method:

 

 public static class StrignBuilderExtensions    {        public static int IndexOf(StringBuilder sb, char value)        {            for (int i = 0; i < sb.Length; i++)            {                if (sb[i] == value)                    return i;            }            return -1;        }    }

 

After defining the haipi method, you can use it in the code, as shown below:

 

            StringBuilder sb = new StringBuilder("Hello,my name is");            int index = StrignBuilderExtensions.IndexOf(sb.Replace(‘,‘, ‘!‘), ‘!‘);

 

The above Code seems to have no problem, but it is not ideal for programmers. The first problem is that to obtain a character in a stringbuilder for indexing, you must know that strignbuilderextensions exists. The second problem is that the Code does not reflect the sequence of operations executed on the stringbuilder object, make codes hard to write, read, and maintain. We want to call replace first, and then call indexof, but read the last line of code from left to right. The first line is indexof, and then we can see replace. Of course, you can write the code below, and the behavior of the code looks easy to understand.

 

  sb.Replace(‘,‘, ‘!‘);            int index = StrignBuilderExtensions.IndexOf(sb, ‘!‘);

 

However, both versions affect our understanding of code behavior. Strignbuilderextensions seems to be a problem, which makes it impossible for us to focus on the operations to be executed. If the stringbuilder class internally defines the indexof method, we can rewrite the above Code:

 

 int i = sb.Replace(‘,‘, ‘!‘).IndexOf(‘!‘);

 

With this example, you can easily understand what the C # extension method does. It allows you to define a static method and call it using the syntax of the instance method. In other words, you can now define your own indexof method. To convert indexof into an extension method, you only need to add the this keyword before the first parameter.

 

  public static class StrignBuilderExtensions    {        public static int IndexOf(this StringBuilder sb, char value)        {            for (int i = 0; i < sb.Length; i++)            {                if (sb[i] == value)                    return i;            }            return -1;        }    }

 

Now, when the compiler sees the following code:

 

int index=sb.IndexOf(‘x‘);

 

It first checks whether the stringbuilder class or any of its base classes provide the instance method for obtaining a single char parameter named indexof. If such an instance method exists, the compiler will generate the Il code to call it.

If no matching instance method is found, check whether any static class defines a static method named indexof, her first parameter is a type that matches the expression type of the method currently called, and this key word must be used for this type.

[C #] Extension Method

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.