为什么有一个私有构造函数 [英] Why have a private constructor
本文介绍了为什么有一个私有构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么要有一个私有构造函数?
Why would you have a private constructor?
他们有什么好处,何时以及为什么要使用公共构造函数。
What benifits are there from them, and when and why would you use it over a public constructor.
推荐答案
(因为dupe不是特定于C#的)
(Because the dupe isn't specific to C#)
- 在.NET 2.0之前,是一个使类静态的伎俩。私人ctor阻止实例化。
- 创建Singleton模式。实例化可以通过GetInstance成员控制。
- 要重新使用和/或控制构造函数代码:
class Foo
{
private Foo() { /* common ctor code */ }
public Foo(int x) : this() { /* from int */ }
protected Foo(string s) : this() { /* from string */ }
}
这篇关于为什么有一个私有构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文