本文實(shí)例分析了ASP.NET私有構(gòu)造函數(shù)用法。分享給大家供大家參考。具體分析如下:
一、私有構(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ù)的特性也可以用于管理對(duì)象的創(chuàng)建。雖然私有構(gòu)造函數(shù)不允許外部方法實(shí)例化這個(gè)類,但卻允許此類中的公共方法(有時(shí)也稱為工廠方法,factory method)創(chuàng)建對(duì)象。也就是說,類可以創(chuàng)建自身的實(shí)例、控制外界對(duì)它的訪問,以及控制創(chuàng)建的實(shí)例個(gè)數(shù)
二、私有構(gòu)造函數(shù)作用實(shí)例說明
1、帶私有構(gòu)造函數(shù)的類不能被繼承
在Animal類中聲明一個(gè)私有構(gòu)造函數(shù),讓Dog類來繼承Animal類。
復(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)行如下測試代碼:
復(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)方法。
復(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();
}
}
希望本文所述對(duì)大家的asp.net程序設(shè)計(jì)有所幫助。
您可能感興趣的文章:- asp.net 枚舉文件里面的數(shù)字綁定到DropDownList里面去
- .NET中StringBuilder用法實(shí)例分析
- .NET中的異常和異常處理用法分析
- .NET中的IO操作之文件流用法分析
- ASP.NET中repeater控件用法實(shí)例
- Asp.Net中索引器的用法分析
- ASP.NET中 script runat server 的用法
- ASP.NET中TimeSpan的用法實(shí)例解析
- .NET中的枚舉用法淺析