C # Extension Method)

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.