An extension method is a special static method that does not have to create a new derived class and recompile the original type.
Example: Judging whether it is a weekend or a working day
New DateTime (42); Switch (datetime.dayofweek) { case dayofweek.saturday: case DayOfWeek.Sunday: returntrue; default : return false ;}
If you want to reduce the duplication of code, you can write helper classes
Public Static classdatetimehelper{ Public Static BOOLisweekend (datetime datetime) {Switch(datetime.dayofweek) { CaseDayofweek.saturday: CaseDayOfWeek.Sunday:return true; default: return false; } }}
Call
if (datetimehelper.isweekend (date)) Weekendprocessing (); Else weekdayprocessing ();
To use the extension method:
Public Static classdatetimeextensions{ Public Static BOOLIsweekend ( Thisdatetime datetime) { Switch(datetime.dayofweek) { CaseDayofweek.saturday: CaseDayOfWeek.Sunday:return true; default: return false; } }}
The difference is that one of the parameters of the method needs to use the This keyword, which indicates that the extended class also needs to be aware that a static method must not be the same as the existing method signature
Call:
New DateTime (44); if (date. Isweekend ()) weekendprocessing (); Else weekdayprocessing ();
The Isweekend () method is used as part of the DateTime method to accumulate the method and the convenience.
Don't forget to go in when you finally use the namespace of the extension class
C # Extension methods