退伍军人请原谅我提出愚蠢的问题.我知道具有私有构造函数的类会阻止实例创建.
class InterestRate
{
// static constructor
static InterestRate()
{
}
//private constructor
private InterestRate()
{
}
// private overloaded constructor
private InterestRate(double d1,double d2)
{
}
// overloaded constructor
public InterestRate(int a,int b)
{
Console.WriteLine("a={0},b={0}",a,b);
}
}
static void Main()
{
//As it is private constructor invokation i can not create a instance
InterestRate firstInstance=new InterestRate();
// non-private overloaded constructor allow me to craete instance
InterestRate r=new InterestRate(10,10);
}
Run Code Online (Sandbox Code Playgroud)
我的问题是,如果具有私有构造函数的类阻止实例创建,为什么该类支持具有非私有构造函数?
私有构造函数不仅阻止来自外部世界的实例化 - 它们通常允许在类中进行构造.实际上,私有构造函数经常用于防止实例化的唯一原因是避免编译器默认添加公共无参数构造函数.这是私有构造函数阻碍其他调用者的唯一方式.
例如,假设您有一个需要在其构造函数中接受集合的类.公共构造函数可能总是采取防御措施,复制集合.但是,您可能有某些情况下,在类中的代码要创建一个新的实例,并知道它并不需要复制的集合,只是参考.这只是私有构造函数很有意义的一种情况.
它确实取决于具体情况.
| 归档时间: |
|
| 查看次数: |
669 次 |
| 最近记录: |