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.