Static class in C#: Best Practice and Trap
The use of static classes has always been the focus of discussion of developers. Although MSDN provides some basic examples, it still needs to be more understandable to use it correctly.
When to use the static class
Static class is good at organizing the following types of functions:
Functions that have nothing to do with specific objects.
- Simplify the implementation by avoiding the creation of objects before calling.
- Make sure that the relevant methods are meaningful, similar to the Math class in the System named space.
-
When to avoid using the static class
However, there are some shortcomings in static classes:
Polymorphism:
Static methods cannot be rewritten or derived, which limits flexibility and scalability.
- The interface is not available: Static methods cannot be accessed by interface declarations, and cannot be used for strategic patterns and interface -based contracts.
Test challenge: - Unable to rewrite the static method to make the creation of test classes and replace the production code with analog objects.
Swelling:
Static tool classes often accumulate unrelated functions, resulting in code expansion and difficulty in maintaining. -
Excessive parameters: Static methods usually have many parameters, including optional parameters, resulting in complex and chaotic code.
- Unnecessary category instance: Forcing the creation object only to access the static method will cause unnecessary expenses when there is actually no instance.
- The exception
Despite these problems, the static method is still applicable in some cases: -
Real tool class:
Class with special uses, execution does not cause a practical program function to expand or damage the maintenance of the code.
One -time project: In projects that have no expected long -term maintenance needs, static methods can speed up development.
Summary
- Whether to use static classes requires careful weighing its potential shortcomings. A balanced standards for the use of static classes in the code library to form a clear standard for the use of static classes in the code library.
The above is the detailed content of When Should You Use Static Classes in C# and When Should You Avoid Them?. For more information, please follow other related articles on the PHP Chinese website!