解析C#中的私有構(gòu)造函數(shù)和靜態(tài)構(gòu)造函數(shù)
私有構(gòu)造函數(shù)
私有構(gòu)造函數(shù)是一種特殊的實(shí)例構(gòu)造函數(shù)。它通常用在只包含靜態(tài)成員的類中。如果類具有一個(gè)或多個(gè)私有構(gòu)造函數(shù)而沒有公共構(gòu)造函數(shù),則其他類(除嵌套類外)無法創(chuàng)建該類的實(shí)例。例如:
class NLog { // Private Constructor: private NLog() { } public static double e = Math.E; //2.71828... }
聲明空構(gòu)造函數(shù)可阻止自動(dòng)生成默認(rèn)構(gòu)造函數(shù)。注意,如果您不對構(gòu)造函數(shù)使用訪問修飾符,則在默認(rèn)情況下它仍為私有構(gòu)造函數(shù)。但是,通常顯式地使用 private 修飾符來清楚地表明該類不能被實(shí)例化。
當(dāng)沒有實(shí)例字段或?qū)嵗椒ǎㄈ?Math 類)時(shí)或者當(dāng)調(diào)用方法以獲得類的實(shí)例時(shí),私有構(gòu)造函數(shù)可用于阻止創(chuàng)建類的實(shí)例。如果類中的所有方法都是靜態(tài)的,可考慮使整個(gè)類成為靜態(tài)的。
下面是使用私有構(gòu)造函數(shù)的類的示例。
public class Counter { private Counter() { } public static int currentCount; public static int IncrementCount() { return ++currentCount; } } class TestCounter { static void Main() { // If you uncomment the following statement, it will generate // an error because the constructor is inaccessible: // Counter aCounter = new Counter(); // Error Counter.currentCount = 100; Counter.IncrementCount(); Console.WriteLine("New count: {0}", Counter.currentCount); // Keep the console window open in debug mode. Console.WriteLine("Press any key to exit."); Console.ReadKey(); } }
輸出:
New count: 101
注意,如果您取消注釋該示例中的以下語句,它將生成一個(gè)錯(cuò)誤,因?yàn)樵摌?gòu)造函數(shù)受其保護(hù)級(jí)別的限制而不可訪問:
// Counter aCounter = new Counter(); // Error
靜態(tài)構(gòu)造函數(shù)
靜態(tài)構(gòu)造函數(shù)用于初始化任何靜態(tài)數(shù)據(jù),或用于執(zhí)行僅需執(zhí)行一次的特定操作。在創(chuàng)建第一個(gè)實(shí)例或引用任何靜態(tài)成員之前,將自動(dòng)調(diào)用靜態(tài)構(gòu)造函數(shù)。
class SimpleClass { // Static variable that must be initialized at run time. static readonly long baseline; // Static constructor is called at most one time, before any // instance constructor is invoked or member is accessed. static SimpleClass() { baseline = DateTime.Now.Ticks; } }
靜態(tài)構(gòu)造函數(shù)具有以下特點(diǎn):
- 靜態(tài)構(gòu)造函數(shù)既沒有訪問修飾符,也沒有參數(shù)。
- 在創(chuàng)建第一個(gè)實(shí)例或引用任何靜態(tài)成員之前,將自動(dòng)調(diào)用靜態(tài)構(gòu)造函數(shù)來初始化類。
- 無法直接調(diào)用靜態(tài)構(gòu)造函數(shù)。
- 在程序中,用戶無法控制何時(shí)執(zhí)行靜態(tài)構(gòu)造函數(shù)。
靜態(tài)構(gòu)造函數(shù)的典型用途是:當(dāng)類使用日志文件時(shí),將使用這種構(gòu)造函數(shù)向日志文件中寫入項(xiàng)。
靜態(tài)構(gòu)造函數(shù)在為非托管代碼創(chuàng)建包裝類時(shí)也很有用,此時(shí)該構(gòu)造函數(shù)可以調(diào)用 LoadLibrary 方法。
如果靜態(tài)構(gòu)造函數(shù)引發(fā)異常,運(yùn)行時(shí)將不會(huì)再次調(diào)用該構(gòu)造函數(shù),并且在程序運(yùn)行所在的應(yīng)用程序域的生存期內(nèi),類型將保持未初始化。
在此示例中,類 Bus 有一個(gè)靜態(tài)構(gòu)造函數(shù)。創(chuàng)建 Bus 的第一個(gè)實(shí)例(bus1)時(shí),將調(diào)用該靜態(tài)構(gòu)造函數(shù)來初始化該類。輸出示例驗(yàn)證了即使創(chuàng)建 Bus 的兩個(gè)實(shí)例,該靜態(tài)構(gòu)造函數(shù)也僅運(yùn)行一次,并且在實(shí)例構(gòu)造函數(shù)運(yùn)行之前運(yùn)行。
public class Bus { // Static variable used by all Bus instances. // Represents the time the first bus of the day starts its route. protected static readonly DateTime globalStartTime; // Property for the number of each bus. protected int RouteNumber { get; set; } // Static constructor to initialize the static variable. // It is invoked before the first instance constructor is run. static Bus() { globalStartTime = DateTime.Now; // The following statement produces the first line of output, // and the line occurs only once. Console.WriteLine("Static constructor sets global start time to {0}", globalStartTime.ToLongTimeString()); } // Instance constructor. public Bus(int routeNum) { RouteNumber = routeNum; Console.WriteLine("Bus #{0} is created.", RouteNumber); } // Instance method. public void Drive() { TimeSpan elapsedTime = DateTime.Now - globalStartTime; // For demonstration purposes we treat milliseconds as minutes to simulate // actual bus times. Do not do this in your actual bus schedule program! Console.WriteLine("{0} is starting its route {1:N2} minutes after global start time {2}.", this.RouteNumber, elapsedTime.TotalMilliseconds, globalStartTime.ToShortTimeString()); } } class TestBus { static void Main() { // The creation of this instance activates the static constructor. Bus bus1 = new Bus(71); // Create a second bus. Bus bus2 = new Bus(72); // Send bus1 on its way. bus1.Drive(); // Wait for bus2 to warm up. System.Threading.Thread.Sleep(25); // Send bus2 on its way. bus2.Drive(); // Keep the console window open in debug mode. System.Console.WriteLine("Press any key to exit."); System.Console.ReadKey(); } }
輸出:
Static constructor sets global start time to 3:57:08 PM. Bus #71 is created. Bus #72 is created. 71 is starting its route 6.00 minutes after global start time 3:57 PM. 72 is starting its route 31.00 minutes after global start time 3:57 PM.
上一篇:解析C#編程的通用結(jié)構(gòu)和程序書寫格式規(guī)范
欄 目:C#教程
下一篇:C#編程中使用ref和out關(guān)鍵字來傳遞數(shù)組對象的用法
本文標(biāo)題:解析C#中的私有構(gòu)造函數(shù)和靜態(tài)構(gòu)造函數(shù)
本文地址:http://mengdiqiu.com.cn/a1/C_jiaocheng/6747.html
您可能感興趣的文章
- 01-10C#中查找Dictionary中的重復(fù)值的方法
- 01-10C#將圖片存放到SQL SERVER數(shù)據(jù)庫中的方法
- 01-10關(guān)于nancy中的身份驗(yàn)證
- 01-10C#中的事務(wù)用法實(shí)例分析
- 01-10C#實(shí)現(xiàn)讀取DataSet數(shù)據(jù)并顯示在ListView控件中的方法
- 01-10C#中的正則表達(dá)式介紹
- 01-10C#開發(fā)中的垃圾回收機(jī)制簡析
- 01-10C#語言中的修飾符匯總
- 01-10C#中的 == 和equals()區(qū)別淺析
- 01-10C#通過正則表達(dá)式實(shí)現(xiàn)提取網(wǎng)頁中的圖片


閱讀排行
本欄相關(guān)
- 01-10C#通過反射獲取當(dāng)前工程中所有窗體并
- 01-10關(guān)于ASP網(wǎng)頁無法打開的解決方案
- 01-10WinForm限制窗體不能移到屏幕外的方法
- 01-10WinForm繪制圓角的方法
- 01-10C#實(shí)現(xiàn)txt定位指定行完整實(shí)例
- 01-10WinForm實(shí)現(xiàn)仿視頻 器左下角滾動(dòng)新
- 01-10C#停止線程的方法
- 01-10C#實(shí)現(xiàn)清空回收站的方法
- 01-10C#通過重寫Panel改變邊框顏色與寬度的
- 01-10C#實(shí)現(xiàn)讀取注冊表監(jiān)控當(dāng)前操作系統(tǒng)已
隨機(jī)閱讀
- 04-02jquery與jsp,用jquery
- 01-11ajax實(shí)現(xiàn)頁面的局部加載
- 08-05織夢dedecms什么時(shí)候用欄目交叉功能?
- 01-10delphi制作wav文件的方法
- 08-05dedecms(織夢)副欄目數(shù)量限制代碼修改
- 08-05DEDE織夢data目錄下的sessions文件夾有什
- 01-10SublimeText編譯C開發(fā)環(huán)境設(shè)置
- 01-10使用C語言求解撲克牌的順子及n個(gè)骰子
- 01-11Mac OSX 打開原生自帶讀寫NTFS功能(圖文
- 01-10C#中split用法實(shí)例總結(jié)