亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

ASP.NET私有構(gòu)造函數(shù)用法分析

 更新時間:2014年11月07日 09:44:27   投稿:shichen2014  
這篇文章主要介紹了ASP.NET私有構(gòu)造函數(shù)用法,較為詳細(xì)的分析了ASP.NET中私有構(gòu)造函數(shù)的特性及具體用法,需要的朋友可以參考下

本文實例分析了ASP.NET私有構(gòu)造函數(shù)用法。分享給大家供大家參考。具體分析如下:

一、私有構(gòu)造函數(shù)的特性
 
1、一般構(gòu)造函數(shù)不是私有或者保護(hù)成員,但構(gòu)造函數(shù)可以使私有成員函數(shù),在一些特殊的場合,會把構(gòu)造函數(shù)定義為私有或者保護(hù)成員。

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();
    }
}

希望本文所述對大家的asp.net程序設(shè)計有所幫助。

相關(guān)文章

最新評論