以下是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.

对我来说,这个例子似乎没有涵盖静态类的很多可能的使用场景。在过去,我曾将静态类用于相关函数的无状态套件,但仅此而已。那么,在什么情况下应该(和不应该)将类声明为静态的呢?


当前回答

我只对辅助方法使用静态类,但随着c# 3.0的出现,我更愿意为这些方法使用扩展方法。

我很少使用静态类方法,原因与我很少使用单例“设计模式”相同。

其他回答

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保持联系,你就永远不会出错!

对于c# 3.0,扩展方法可能只存在于顶级静态类中。

我确实倾向于为工厂使用静态类。例如,这是我的一个项目中的日志类:

public static class Log
{
   private static readonly ILoggerFactory _loggerFactory =
      IoC.Resolve<ILoggerFactory>();

   public static ILogger For<T>(T instance)
   {
      return For(typeof(T));
   }

   public static ILogger For(Type type)
   {
      return _loggerFactory.GetLoggerFor(type);
   }
}

您甚至可能已经注意到IoC是使用静态访问器调用的。对我来说,大多数时候,如果你可以调用一个类的静态方法,这就是你能做的一切,所以我把类标记为静态,以额外的清晰。

我只对辅助方法使用静态类,但随着c# 3.0的出现,我更愿意为这些方法使用扩展方法。

我很少使用静态类方法,原因与我很少使用单例“设计模式”相同。

如果你使用代码分析工具(例如FxCop),如果一个方法不访问实例数据,它会建议你将该方法标记为静态。其基本原理是有性能增益。CA1822 -将成员标记为静态。

这更像是一个指导方针,而不是规则,真的……