San*_*eep 9 .net c# static-constructor private-constructor
我搜索了很多,但没有一个答案是清楚的(至少对我来说!).现在我把这个问题放进去,因为我相信我无法在其他任何地方得到更明确的答案.
我什么时候应该在班上使用私有/静态构造函数?
我厌倦了通常的答案,所以请帮助我一些实时的例子和使用这些构造函数的优点/缺点.
Dan*_*zey 17
静态构造函数:用于初始化静态成员.
私有构造函数:当您只希望从其自己的代码(通常在静态方法中)实例化类时使用.例如:
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()
{
}
}
Run Code Online (Sandbox Code Playgroud)
我什么时候应该在班上使用私人构造函数?
当你想要一个构造函数,但不想将它暴露给世界.这可能是因为你有一个调用构造函数(验证后)工厂方法,或者是因为该构造函数是由构造函数链连接(即所谓的public Foo(string) : this() { ...}).
另外,请注意,反射代码通常能够使用私有构造函数 - 例如序列化或ORM库.
此外,在早期的C#编译器中,当你编写现在的static类时 - 拥有一个私有构造函数是使它看起来不可创建的唯一方法.
我应该什么时候在班上使用静态构造函数?
当您需要在实例或静态方法访问该状态之前初始化某些静态状态.
| 归档时间: |
|
| 查看次数: |
13855 次 |
| 最近记录: |