Home >Backend Development >C++ >Can Extension Methods Be Added to Static Classes in C#?
Can the extension method to the static class in the static class?
The expansion method in C# is a powerful feature that allows adding a new method to the existing type without having to modify its source code. However, the question is whether it can expand such a static class like .
Try to use the local static method of the "This" parameter to expand Console
and add a
Console
The reason for this failure is the inherent characteristics of the expansion method. They need instance variables (values) of objects to play a role. On the other hand, static classes represent global state and lack instance data. Therefore, it is not feasible to use an instance -based expansion method. Console
WriteBlueLine
However, there is another solution: creating a static packaging class around the static
For example, the class that can be realized
, as shown below: ConfigurationManager
Through the call method, the code can avoid repeating the inconvenience of ConfigurationManagerWrapper
.
The above is the detailed content of Can Extension Methods Be Added to Static Classes in C#?. For more information, please follow other related articles on the PHP Chinese website!