我只是想知道静态构造函数和私有构造函数之间的主要区别.
我知道Static Constructor用于初始化类的静态成员.静态构造函数无法访问非静态成员.它在类的第一个实例之前执行.我们无法确定执行的时间.静态构造函数由CLR执行,而不是由类的对象执行.没有参数化的静态构造函数,因为它由CLR而不是由对象处理.执行时间可能是加载包含的程序集.
但是,Private Constructor用于限制要实例化和继承的类.只要类只包含静态成员,就会使用私有构造函数.
除此之外,这两者在内存使用和其他方面有什么区别?哪个应该用?
私有构造函数仍然是实例构造函数 - 它们不是静态的.它们与公共构造函数没有什么不同,除了它们定义谁可以调用它们,就像公共和私有常规方法之间的区别一样.
私有构造函数的一些可能用例是单例,私有构造函数,其功能由多个公共构造函数共享,或者使用静态方法来构建类而不是构造函数.
public class Bar {
private Bar() { }
private static readonly Bar _instance = new Bar();
public static Bar GetInstance() { return _bar; }
}
public class Baz {
private string _msg;
private Baz(string msg) { // Not accessible publicly
_msg = msg;
}
// These two are accessible publicly, and both call
// the private constructor
public Baz(int i) : this(i + " is an integer") { }
public Baz(decimal d) : this(d + " is a decimal") { }
}
public class Foo {
private Foo() { // Not accessible publicly
}
public static Foo CreateFoo() {
// Do some stuff here that you can't normally do in a constructor.
return new Foo();
}
}
Run Code Online (Sandbox Code Playgroud)