一、私有構(gòu)造函數(shù)的特性
1、一般構(gòu)造函數(shù)不是私有或者保護(hù)成員,但構(gòu)造函數(shù)可以使私有成員函數(shù),在一些特殊的場合,會(huì)把構(gòu)造函數(shù)定義為私有或者保護(hù)成員。
2、私有構(gòu)造函數(shù)是一種特殊的實(shí)例構(gòu)造函數(shù)。它通常用在只包含靜態(tài)成員的類中。如果類具有一個(gè)或多個(gè)私有構(gòu)造函數(shù)而沒有公共構(gòu)造函數(shù),則不允許其他類(除了嵌套類)創(chuàng)建該類的實(shí)例。
3、私有構(gòu)造函數(shù)的特性也可以用于管理對象的創(chuàng)建。雖然私有構(gòu)造函數(shù)不允許外部方法實(shí)例化這個(gè)類,但卻允許此類中的公共方法(有時(shí)也稱為工廠方法,factory method)創(chuàng)建對象。也就是說,類可以創(chuàng)建自身的實(shí)例、控制外界對它的訪問,以及控制創(chuàng)建的實(shí)例個(gè)數(shù)
二、私有構(gòu)造函數(shù)作用實(shí)例說明
1、帶私有構(gòu)造函數(shù)的類不能被繼承
在Animal類中聲明一個(gè)私有構(gòu)造函數(shù),讓Dog類來繼承Animal類。
C# 代碼 復(fù)制public class Animal
{
PRivate Animal()
{ Console.WriteLine("i am animal");
}
}
public class Dog : Animal {
}
運(yùn)行程序,生成解決方案,報(bào)錯(cuò)如下圖所示:
2、帶私有構(gòu)造函數(shù)的類不能被實(shí)例化
運(yùn)行如下測試代碼:
C# 代碼 復(fù)制class Program
{
static void Main(string[] args)
{
Animal animal = new Animal();
}
}
public class Animal
{
private Animal()
{
Console.WriteLine("i am animal");
}
}
程序運(yùn)行后生成解決方案,報(bào)錯(cuò)如下圖所示:
三、私有構(gòu)造函數(shù)的應(yīng)用
有些時(shí)候,我們不希望一個(gè)類被過多地被實(shí)例化,比如有關(guān)全局的類、路由類等。這時(shí)候,我們可以為類設(shè)置構(gòu)造函數(shù)并提供靜態(tài)方法。
C# 代碼 復(fù)制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();
}
}
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注