[Original] extension method basic usage

Source: Internet
Author: User

Objective

First, let's look at the explanation above MSDN: extension methods enable you to "add" methods to existing types without creating new derived types, recompiling, or otherwise modifying the original type.

In fact, it is the Microsoft Class Library, we can't modify, but we can give these class libraries a way to add some of our methods.

1.0 extension Method Scenarios
DateTime now = DateTime.Now; // 1.0 format now as YYYY-MM-DD output string fmtstr = Now. Tostring ("Yyyy-mm-dd");
2.0 format now as YYYY-MM-DD HH:MM:SS output
String fmtstr1 = Now. Tostring ("Yyyy-mm-dd");

Now there's only one time here. No problem, if thousands of times are used in our system? What should we do at this time, smart you, must have thought of writing a method ...

   Public Static classExthelper { Public Static stringFMTDATAYYYYMMDD (DateTime now)        {            returnNow. ToString ("YYYY-MM-DD"); }         Public Static stringFMTDATAYYYYMMDDHHMMSS (DateTime Now) {            returnNow. ToString ("YYYY-MM-DD HH:mm:ss"); }    }

After the transformation, the above code can be rewritten as follows:

DateTime now = DateTime.Now; // 1.0 format now as YYYY-MM-DD output string fmtstr = EXTHELPER.FMTDATAYYYYMMDD (now); // 2.0 format now as YYYY-MM-DD HH:mm:ss output string fmtstr1 =exthelper.fmtdatayyyymmddhhmmss (now);

But programmers are very lazy, then we have to remember this exthelper, think we have no better way, if we can now. The method name is good, the extension method can meet our requirements ...

2.0 extension methods three elements

Steps for how to extend a method:
1, must be placed in a static class
2. The method must be a static method
3, the first parameter of the method is a type parameter, use this start

The modified Exthelper class

     Public Staticclass exthelper { Public StaticstringFMTDATAYYYYMMDD ( ThisDateTime now)        {            returnNow. ToString ("YYYY-MM-DD"); }         Public Static stringFMTDATAYYYYMMDDHHMMSS ( ThisDateTime Now) {            returnNow. ToString ("YYYY-MM-DD HH:mm:ss"); }    }

The call is as follows:

DateTime now = DateTime.Now; // 1.0 format now as YYYY-MM-DD output string fmtstr = now.fmtdatayyyymmdd (); // 2.0 format now as YYYY-MM-DD HH:mm:ss output string fmtstr1 = Now.fmtdatayyyymmddhhmmss ();
3.0 features of the extension method

1, the extension method priority is lower than the instance method

    public static class Exthelper    {public        static string ToUpper (this string str)        {            return str. ToUpper ();        }    }

We all know that there is a ToUpper method above the string, and if we are defining an extension method at this point, this method will not work ...

2. Extension methods can be overloaded with instance methods to form methods

public static class Exthelper    {        int num)        {            return str. ToUpper () + num;        }    }

At this point, if we have our own business logic, then we can make an overload with the instance method ...

3, the extension method defined above the parent class, can be used on the subclass object

  Public InterfaceIpig {} Public classPig:ipig {Private string_name;  Public stringName {Get            {                return_name; }            Set            {                if(value.) Length >=2) {_name=value; }                Else                {                    //Throw Exception                }            }        }        //Automatic Properties         Public intAge {Get; Set; }    }     Public classSmallpig:pig {}
public static class Exthelper    {public        static string Get (this pig pig)        {            return pig. Name;        }    }

Subclasses can also point out extension methods

var pig = new Pig (); Pig. Get (); var spig = new Smallpig (); Spig. Get ();

4, define the extension method above the interface, can be used on the implementation class object (Ef,mvc use very frequently)

public static class Exthelper    {public        static void Set (this ipig ipig)        {                }    }

The interface implementation class can also point out the expansion method. Extension methods in iqueryable<t> in MVC, using in dbset<t>

            var pig = new Pig ();            Pig. Get ();            Pig. Set ();            var spig = new Smallpig ();            Spig. Get ();            Spig. Set ();

  

If you feel good after reading this article, please click " attention " in the upper left corner to support the blogger, thank you!

If you feel good reading this article, please click on the bottom right corner of the "recommended"

Feng Ling Yi

QQ: 616931

Source:Http://www.cnblogs.com/fenglingyi

statement: The copyright of this article is owned by the author and the blog park, without the author's consent must retain the statement, and in the article page obvious location to the original link, otherwise reserve the right to pursue legal responsibility

[Original] extension method basic usage

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.