C # easily overlooked knowledge points (4)

Source: Internet
Author: User

19. Extensions

For example, if you want to add a new method to a class, but for some reason, you cannot directly modify the source code of the class. You can implement the method by extending the class.

An example is as follows:

Suppose there is a class show

1 public class show 2 {3 Public void methodone () 4 {5 console. writeline ("methodone"); 6} 7} 8 9 // extended class 10 public static class showextension11 {12 public static void methodtwo (this show s) // The first parameter is the type to be extended. After the keyword this, the compiler will know that this method is part of the show type. 13 {14 console. writeline ("methodtwo"); 15} 16} 17 18 19 class program20 {21 static void main () 22 {23 show s = new show (); 24 s. methodone (); 25 s. methodtwo (); // when calling the method of the extension class, the first parameter does not need to be processed. Although the extension method is static, it must be called using the standard instance method syntax. 26 console. Read (); 27} 28}

Note: If the extension method has the same name as a method in the class, the extension method is not called. Any existing instance methods in the class are preferred.

 

20,

 

C # easily overlooked knowledge points (4)

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.