以下是MSDN在“何时使用静态类”一节中所说的:
static class CompanyInfo
{
public static string GetCompanyName() { return "CompanyName"; }
public static string GetCompanyAddress() { return "CompanyAddress"; }
//...
}
Use a static class as a unit of
organization for methods not
associated with particular objects.
Also, a static class can make your
implementation simpler and faster
because you do not have to create an
object in order to call its methods.
It is useful to organize the methods
inside the class in a meaningful way,
such as the methods of the Math class
in the System namespace.
对我来说,这个例子似乎没有涵盖静态类的很多可能的使用场景。在过去,我曾将静态类用于相关函数的无状态套件,但仅此而已。那么,在什么情况下应该(和不应该)将类声明为静态的呢?
When deciding whether to make a class static or non-static you need to look at what information you are trying to represent. This entails a more 'bottom-up' style of programming where you focus on the data you are representing first. Is the class you are writing a real-world object like a rock, or a chair? These things are physical and have physical attributes such as color, weight which tells you that you may want to instantiate multiple objects with different properties. I may want a black chair AND a red chair at the same time. If you ever need two configurations at the same time then you instantly know you will want to instantiate it as an object so each object can be unique and exist at the same time.
On the other end, static functions tend to lend more to actions which do not belong to a real-world object or an object that you can easily represent. Remember that C#'s predecessors are C++ and C where you can just define global functions that do not exist in a class. This lends more to 'top-down' programming. Static methods can be used for these cases where it doesn't make sense that an 'object' performs the task. By forcing you to use classes this just makes it easier to group related functionality which helps you create more maintainable code.
大多数类既可以用静态的也可以用非静态的来表示,但是当你有疑问时,只要回到OOP的根源,试着想想你在表示什么。这是一个正在执行动作的对象(一辆可以加速、减速、转弯的汽车)还是更抽象的对象(比如显示输出)?
与你的内部OOP保持联系,你就永远不会出错!