C#靜態(tài)構(gòu)造函數(shù)特點(diǎn)淺析
C#靜態(tài)構(gòu)造函數(shù)的特點(diǎn)是什么呢?讓我們首先來(lái)了解下C#靜態(tài)構(gòu)造函數(shù):
C#靜態(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 constructor
- static SimpleClass() { //... }}
C#靜態(tài)構(gòu)造函數(shù)具有以下特點(diǎn):
C#靜態(tài)構(gòu)造函數(shù)既沒(méi)有訪問(wèn)修飾符,也沒(méi)有參數(shù)。
在創(chuàng)建第一個(gè)實(shí)例或引用任何靜態(tài)成員之前,將自動(dòng)調(diào)用靜態(tài)構(gòu)造函數(shù)來(lái)初始化類。
無(wú)法直接調(diào)用靜態(tài)構(gòu)造函數(shù)。
在程序中,用戶無(wú)法控制何時(shí)執(zhí)行靜態(tài)構(gòu)造函數(shù)。
C#靜態(tài)構(gòu)造函數(shù)的典型用途是:當(dāng)類使用日志文件時(shí),將使用這種構(gòu)造函數(shù)向日志文件中寫入項(xiàng)。
C#靜態(tài)構(gòu)造函數(shù)在為非托管代碼創(chuàng)建包裝類時(shí)也很有用,此時(shí)該構(gòu)造函數(shù)可以調(diào)用 LoadLibrary 方法。
C#靜態(tài)構(gòu)造函數(shù)示例
在此示例中,類 Bus 有一個(gè)靜態(tài)構(gòu)造函數(shù)和一個(gè)靜態(tài)成員 Drive()。當(dāng)調(diào)用 Drive() 時(shí),將調(diào)用靜態(tài)構(gòu)造函數(shù)來(lái)初始化類
- public class Bus{
- // Static constructor:
- static Bus() {
- System.Console.WriteLine(
- "The static constructor invoked.");
- }
- public static void Drive() { System.Console.WriteLine(
- "The Drive method invoked.");
- }
- }
- class TestBus{
- static void Main() {
- Bus.Drive();
- }
- }
C#靜態(tài)構(gòu)造函數(shù)示例之輸出:
- The static constructor invoked.
- The Drive method invoked.
C#靜態(tài)構(gòu)造函數(shù)的特點(diǎn)就向你介紹到這里,希望對(duì)你學(xué)習(xí)了解C#靜態(tài)構(gòu)造函數(shù)有所幫助。
【編輯推薦】