您好,登錄后才能下訂單哦!
本篇文章為大家展示了私有構(gòu)造函數(shù)怎么在ASP.NET中使用,內(nèi)容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細(xì)介紹希望你能有所收獲。
一、私有構(gòu)造函數(shù)的特性
1、一般構(gòu)造函數(shù)不是私有或者保護成員,但構(gòu)造函數(shù)可以使私有成員函數(shù),在一些特殊的場合,會把構(gòu)造函數(shù)定義為私有或者保護成員。
2、私有構(gòu)造函數(shù)是一種特殊的實例構(gòu)造函數(shù)。它通常用在只包含靜態(tài)成員的類中。如果類具有一個或多個私有構(gòu)造函數(shù)而沒有公共構(gòu)造函數(shù),則不允許其他類(除了嵌套類)創(chuàng)建該類的實例。
3、私有構(gòu)造函數(shù)的特性也可以用于管理對象的創(chuàng)建。雖然私有構(gòu)造函數(shù)不允許外部方法實例化這個類,但卻允許此類中的公共方法(有時也稱為工廠方法,factory method)創(chuàng)建對象。也就是說,類可以創(chuàng)建自身的實例、控制外界對它的訪問,以及控制創(chuàng)建的實例個數(shù)
二、私有構(gòu)造函數(shù)作用實例說明
1、帶私有構(gòu)造函數(shù)的類不能被繼承
在Animal類中聲明一個私有構(gòu)造函數(shù),讓Dog類來繼承Animal類。
復(fù)制代碼 代碼如下:
public class Animal
{
private Animal()
{ Console.WriteLine("i am animal");
}
}
public class Dog : Animal {
}
運行程序,生成解決方案,報錯如下圖所示:
2、帶私有構(gòu)造函數(shù)的類不能被實例化
運行如下測試代碼:
復(fù)制代碼 代碼如下:
class Program
{
static void Main(string[] args)
{
Animal animal = new Animal();
}
}
public class Animal
{
private Animal()
{
Console.WriteLine("i am animal");
}
}
程序運行后生成解決方案,報錯如下圖所示:
三、私有構(gòu)造函數(shù)的應(yīng)用
有些時候,我們不希望一個類被過多地被實例化,比如有關(guān)全局的類、路由類等。這時候,我們可以為類設(shè)置構(gòu)造函數(shù)并提供靜態(tài)方法。
復(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();
}
}
上述內(nèi)容就是私有構(gòu)造函數(shù)怎么在ASP.NET中使用,你們學(xué)到知識或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識儲備,歡迎關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。