静态类的好处 [英] benefits of a static class
本文介绍了静态类的好处的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能重复:结果
的什么是使用静态类
什么是声明静态类的好处是什么?
What are the benefits of declaring a static class?
public static class MyStaticClass
{
}
是否有比它不能被实例化?结果$ b其他任何$ b你否则为什么需要一个静态类,什么原因,应该一类是静态的?结果
是任何种类应被声明为静态的,除非它的意思被实例化一个很好的经验规则?
Are there any other than "it can't be instantiated"?
Why else would you want a static class, for what reasons should a class be static?
Is "any class should be declared as static unless it's meant to be instantiated" a good rule of thumb?
推荐答案
如果一个类有static修饰符,则:
If a class has the static modifier then:
- 它使你的意图明显:这不只是碰巧有所有静态成员的类 - 这是一个类的将只的有静态成员
- 您阻止实例化的没有的需要私有构造函数只是为了抑制默认公众有一个
- 您不允许声明该类型的变量
- 您不允许使用该类型作为类型参数(IIRC,反正)
- 您可以声明的类型的扩展方法,如果它是一个顶级类型
- It makes your intention clear: this isn't just a class which happens to have all static members - it's a class which will only ever have static members
- You prevent instantiation without needing a private constructor just to suppress the default public one
- You aren't allowed to declare a variable of that type
- You aren't allowed to use that type as a type argument (IIRC, anyway)
- You can declare extension methods in the type if it's a top-level type
第一点是最重要的,虽然,海事组织。你沟通的意图编译器和其他开发人员都。
The first point is the most important though, IMO. You're communicating intent to both the compiler and other developers.
这篇关于静态类的好处的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文