-
C#教程之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();
}