C # Extension Method

Source: Internet
Author: User

The extension method enables you to "add" methods to existing types 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. The above isMsdnThe official website describes the extension method. Now I will explain it through a scenario example. Assume that a console ProgramClass program {}The main functions are as follows:

static void Main(string[] args)        {            DateTime now = DateTime.Now;            string time = now.ToString("yyyy-mm-dd hh:mm:ss");             Console.WriteLine(time);            Console.ReadKey();        }

If the requirement changes, the display format of the date will change"Yyyy-mm-dd"This format, of course, only needs to be initializedTimeYou can simply rewrite it as follows:

string time = now.ToString("yyyy-mm-dd");

But what if there are many classes to change the date format? Should each be changed once? In this way, once the demand changes, it will be very busy. The traditional solution is to encapsulate a helper class, write a method in it, and then call it for other classes.

In this example, addDatehelperClass:Public class datehelper {}, Define the method in the class:

public static string DateToString(DateTime dt)        {            return dt.ToString("yyyy-mm-dd hh:mm:ss");        }

The original main function is rewritten as follows:

static void Main(string[] args)        {            DateTime now = DateTime.Now;            string time = DateHelper.DateToString(now);            Console.WriteLine(time);            Console.ReadKey();        }

In this case, you only need to rewriteDatehelpClassDatetostring ()Method. No matter how many classes call this method, it will be affected. The problem is solved, but it is still a little troublesome to call another class method. Is there any way to make us look likeNow. datetostring ()Is it directly called? Of courseDatetimeIt was written by Microsoft. We couldn't change it and couldn't create the desired instance method, so we introduced the extension method.
The following are the elements of the extension method:

1. This method must be a static method.

2. This method must be placed in a static class.

3. The first parameter of this method must beThisAnd specify the type of the method to be extended.

Based on the above elements, weDatehelperClass to static class:Public static class datehelper {}, Rewrite at the same timeDatetostring ()Method:

public static string DateToString(this DateTime dt)        {            return dt.ToString("yyyy-mm-dd hh:mm:ss");        }

Return to the main function method body and enter"Now ."You can see that there is an automatic promptDatetostring ()Method, so the code can be written as follows:

static void Main(string[] args)        {            DateTime now = DateTime.Now;             string time = now.DateToString();            Console.WriteLine(time);            Console.ReadKey();        }

Obviously, this makes it easier to use, and it makes us look like an instance method of the extended type itself, which is highly readable. The following describes the features of the extension method:

1. The extension method must be a variable of this type to use. Other types cannot be used. In this example, the Extension MethodDatetimeType, it can only beDatetimeType Variable.Out (Now. datetostring ())
2. In the extension methodThisThe following parameters do not belong to the method parameter. In this example, there is no parameter,ThisTheDatetime dtIndicates the type of extension method.
3. If the extension method and instance method have the same signature, the instance method is called first.
4. The method is extended from the parent class and can be directly used by the quilt class object.
5. The extension methods on the Extended Self-interface can be directly used by the objects of the implementation class.
6. The extension method is eventually compiled by the compiler into: static class. Static Method (). In this exampleNow. datetostring ()Will eventually be compiledDatehelper. datetostring (now ),This is its nature

In fact, we may encounter such a situation. For example, when an interface extends a method, all classes that have already implemented this interface must implement new extension methods, this change is a very troublesome task. You can use the extension method to "save the nation". Sometimes we want to add new methods for a class but don't want to change this class, the extension method is a pseudo-add method that reflects its value. The most common extension method is the LINQ standard query operator, which is widely used. This convenient and quick method should win 1024 likes from coders.

 

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.