C#私有构造函数使用示例
声明空构造函数可阻止自动生成默认构造函数。注意,如果您不对构造函数使用访问修饰符,则在默认情况下它仍为私有构造函数。但是,通常显式地使用 private 修饰符来清楚地表明该类不能被实例化。
示例代码:
public class privateconclass
{
private static privateconclass pcc;
private privateconclass()
{
console.writeline("this private constructure function. so you cannot create an instance of this class.");
}
public static privateconclass createpcc()
{
pcc = new privateconclass();
return pcc;
}
public static void showstaticmethod()
{
console.writeline("this is a static method. just be called by class name.");
}
public void showmethod()
{
console.writeline("this is a nonstatic method. just be called by private static instance pcc.");
}
}
class program
{
static void main(string[] args)
{
privateconclass pcc = privateconclass.createpcc();
pcc.showmethod();
privateconclass.showstaticmethod();
}
}
上一篇: C#将时间转成文件名使用方法
下一篇: Java利用数组随机抽取幸运观众如何实现