我搜索了很多次,但没有一个答案是明确的(至少对我来说是这样!)。现在我把这个问题放在 SO 中,因为我相信我无法在其他任何地方得到更明确的答案。
什么时候应该在我的类中使用私有(private)/静态构造函数?
我受够了通常的答案,所以请帮助我提供一些实时示例以及使用这些构造函数的优点/缺点。
最佳答案
静态构造函数:用于初始化静态成员。
私有(private)构造函数:当您只希望一个类在其自己的代码中实例化时使用(通常在静态方法中)。例如:
public class Thing
{
static int Number;
static Thing()
{
Number = 42; // This will only be called once, no matter how many instances of the class are created
}
// This method is the only means for external code to get a new Thing
public static Thing GetNewThing()
{
return new Thing();
}
// This constructor can only be called from within the class.
private Thing()
{
}
}
关于c# - .Net 中的私有(private)构造函数与静态构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13248320/