聲明空構(gòu)造函數(shù)可阻止自動生成默認(rèn)構(gòu)造函數(shù)。注意,如果您不對構(gòu)造函數(shù)使用訪問修飾符,則在默認(rèn)情況下它仍為私有構(gòu)造函數(shù)。但是,通常顯式地使用 private 修飾符來清楚地表明該類不能被實例化。
示例代碼:
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();
}
}
新聞熱點
疑難解答
圖片精選