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