C # Extension methods
I. Extension methods:
1. What is the extension method and what is the role?
Extension methods enable you to "add" methods to an existing type without having to create a new derived type, recompile, or otherwise modify the original type in one way. It still maintains object-oriented features.
2. Features of the extension method:
Static class;
static method;
this keyword;
The class to extend;
parameter (optional)
3. Extension Method Example:
As developers know, customers often change demand, so to be a good programmer must make the programs we develop scalable. Due to the change in requirements below need to give mycalculate class extension a method: Subtract method, the common method is to modify the class of mycalculate directly, if you have the source is good, then if not, will not be helpless, in fact, we do not have to worry about, We can worry about others have thought of, this is the legendary-extension method.
Called in the class:
class program { staticvoid Main (string[] args) { varNew mycalculate (); var sub = My. Subtract (3); Console.WriteLine (sub); Console.readkey (); } }
class to extend the method:
Public class mycalculate { publicstaticint Add (intint num2) { return num1 + num2; } }
Extended classes:
Public Static class mycalculateextension { publicstaticint Subtract ( This mycalculate my,int int num2) { return num1- num2; } }
C # Extension methods