C # extension method,

Source: Internet
Author: User

C # extension method,

There is no such thing in java. Once a class is final, this class can no longer be added to the method, but C # can do this, you can add a new method to the sealed class, I prefer c.

This is the extension method in C.

So under what circumstances do we need to write extension methods for a class?

 

The following are three elements of the Extension Method: (it is also a syntax rule)

  

Here is a chestnut:

We generally Convert a number of the string type to the int type. Generally, we use the int. Parse () method or the Convert method. Can we add a Parse Method to the string type?

Yes, of course. The Code goes up first: (here, only the extension method without parameters is written. If there are parameters, you can directly add them to the parameter list. During the call, the corresponding parameters are passed)

using System;namespace ConsoleApplicationTest{    public static class stringExtensionMethod    {        public static int Parse(this string str)        {            return int.Parse(str);        }    }    class Program    {        static void Main(string[] args)        {            string str = "111";            int i = str.Parse();            Console.WriteLine("i: " + i);        }    }}

It may be hard to understand why there are parameters in the parameter list, but no parameters are passed during the call. I was a bit confused about this, but I just figured it out, isn't there a this keyword? This refers to the current object, that is, the instance of the extended class, that is, the caller of the extension method. Since it is the caller, it must be transmitted as a parameter.

The following describes the features of the extension method:

 

Related Article

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.