我对此进行了很多搜索,但是没有一个回答清晰明了(至少对我来说是这样!)。现在我将这个问题发布到SO上,因为我相信我无法在其他地方得到更明确的答案。
在我的类中什么时候应该使用私有/静态构造函数?
我厌倦了常规的答案,请给我一些实时示例以及使用这些构造函数的优点/缺点。
我对此进行了很多搜索,但是没有一个回答清晰明了(至少对我来说是这样!)。现在我将这个问题发布到SO上,因为我相信我无法在其他地方得到更明确的答案。
在我的类中什么时候应该使用私有/静态构造函数?
我厌倦了常规的答案,请给我一些实时示例以及使用这些构造函数的优点/缺点。
静态构造函数:用于初始化静态成员。
私有构造函数:仅在希望类只能从其自身代码(通常在静态方法中)实例化时使用。例如:
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()
{
}
}
public Foo(string) : this() { ...}
)。静态构造函数用于初始化类的静态成员,当类的第一个实例被创建或首次访问静态成员时调用。
私有构造函数用于如果你有构造函数的重载,并且其中一些只应该被其他构造函数使用。