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