Sometimes there is a sealed class that you can't modify, but you want to extend it (add a method), you can use the extension method at this time. See the following example:
Class Program { Static Void Main ( String [] ARGs) {sealedclass x = New Sealedclass (); console. writeline (X. testmethod ());}} Sealed Class Sealedclass {} Static Class Sealedclassextension { Public Static String Testmethod ( This Sealedclass X ){ Return "" ;}}
Although sealedclass is a sealed class, we still seem to have added a testmethod Method for it. Taking testmethod as an example, the extension method has the following two features:
(1) Static Method
(2) This keyword is used in the parameter.
As for how to extend a class, let's look at an example of an extended interface.
Public Static ClassEnumerable {Public StaticTsource aggregate <tsource> (ThisIenumerable <tsource> source, func <tsource, tsource, tsource>Func );}
We often use containers that execute ienumerable <t>, such as list <t>. These containers can use some methods, such as aggregate, because they execute the ienumerable <t> interface. If the ienumerable <t> interface definition does not contain the aggregate method, aggregate is actually an extension method. It is defined in the static class enumerable.
Therefore, aggregate is an extension method for the ienumerable <t> interface.
Summary:
(1) Pay attention to the syntax of the extension method.
(2) You can expand classes or interfaces.