静态类比。与私有构造函数和所有的静态属性和方法的类?静态、有的、函数、属性

2023-09-02 02:01:30 作者:别等时光非礼了梦想

当我创建的实用工具类我通常创建一个具有私有构造函数,并公开它的所有方法和属性为静态的类。什么是我们的最佳方法呢?什么是我的方式,或创建一个静态类?之间的差异

When I create utility classes I typically create a class that has a private constructor and exposes all of it's methods and properties as static. What's the best approach for this? What's the difference between the way I do or creating a static class?

推荐答案

静态类是自动密封的,所以人不能继承和重写他们的行为。

Static classes are automatically sealed, so people can't inherit and override their behavior.

这是唯一真正的区别(除非在IL一些特别的东西)

That is the only real difference (unless there is something special in the IL)

所以,如果你使用一个静态类,你救自己制作的构造私人,并宣布了密封类的麻烦。

So if you use a static class, you save yourself the trouble of making the constructor private, and declaring the class sealed.

我想补充一点,定义一个类为静态的,是自文档code。库的用户会知道,这个类不应该被实例化,只有静态值。

I would add, that defining a class as static, is "self-documenting" code. Users of your library will know that this class should not be instantiated, and only has static values.