[C #] make rational use of the "pollution" feature of the Extension Method

Source: Internet
Author: User

The C # Extension Method feature allows us to expand the functions of a class without source code, although there are some restrictions (for example, it can only be an instance method, but it is a good mechanism to enhance code flexibility. The most important thing to pay attention to when using the extension method is "pollution": Once a class is extended, all classes derived from this class will have the extension at the same time, if the symbols are the same, the extension method overwrites the original method in the class. For example, if the ToString () method of the Object class is added, the ToString () method of almost all classes in C # will be replaced with the extended version. "Pollution" only needs to pay more attention and make good use of it to produce amazing results. For example, an example of a messaging system in a game:

Public abstract class Message {} public static class Message_Extension {public static T Broadcast <T> (this T msg) where T: Message {// deliver the message to all }}

 

The above extension uses "pollution" and only requires one definition. All submessage types derived from messages have the Broadcast method, in addition, this method can maintain the type information of the message subclass itself (which has great significance for other generic applications), which is not achieved by traditional class inheritance.

Related Article

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.