C # Programming (21)----------extension methods

Source: Internet
Author: User

extension Methods in C #

There are many ways to extend classes.If there is a source code for the class,Inheritance is a good way to add functionality to a class.But if there is no source code,What to do? eat excrement you can use the extension method , It allows to change a class , but does not need the source code of the class . extension method is static method , It is part of the class , but not actually put in the source code of the class . For example I have a money , Do not know source code , need a addtoamount (decimal amounttoadd).

We can do this :

Namespace Wrox

{

public static Class Moneyextension

{

public static void Addtoamount (this money money,decimal amounttoadd)

{

Money. Amount+=amounttoadd;

}

}

}

AttentionAddtoamount ()Parameters of the method.For extension methods, The first parameter is the type to be extended , It is placed in this After the keyword . tell compiler , This method is money. ,money is the type to be extended . In the extension method , You can access all the common methods and properties of the extended type

In the main program , the Addtoamount () method looks like a method of screwing . It does not display the first parameter , nor does it handle any of it . To use the new method , as with other methods :

Monet cash=new money ();

Cash. Addtoamount (100m);

If the extension method has the same name as a method in the class , the extension method is never called . Any instance methods already in the class are preferred .

C # Programming (21)----------extension methods

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.