C #3.0 "Extension Method"

Source: Internet
Author: User

Added the code extension mechanism "Extension Method" in C #3.0. If you want to extend an existing type, but for some reason it is not convenient to directly modify the source code, you can use the extension method, the original type of extension method is written in other types to complete the extension, which greatly enhances the C # language code extension method and is very convenient to use.

To use the extension method, note the following: the extension method cannot access the original type of private data. The extension method can only be written as the static method form of the static class. Before the extension method allows parameters and the first parameter of the extension method parameter, you need to add "This ", extension method can only be called by the original type object.

Example:

 

Public class employeemodel
{
Private int _ basepaid = 950;

Public int age
{
Get
{
Return _ basepay;
}
}
}

Public static class samplemodelextensions
{
Public static int gettotalpay (this employeemodel model, int normalpay)
{
Return Model. Age + normalpay;
}
}

The call code is:

Employeemodel model = new employeemodel ();
Int totalpay = model. gettotalpay (350 );
This. Literal. Text = "totalpay:" + totalpay. tostring ();

Final Result: totalpay: 1300

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.