国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C# > 正文

解析C#中的私有構造函數(shù)和靜態(tài)構造函數(shù)

2020-01-24 01:18:15
字體:
供稿:網(wǎng)友

私有構造函數(shù)
私有構造函數(shù)是一種特殊的實例構造函數(shù)。它通常用在只包含靜態(tài)成員的類中。如果類具有一個或多個私有構造函數(shù)而沒有公共構造函數(shù),則其他類(除嵌套類外)無法創(chuàng)建該類的實例。例如:

class NLog{  // Private Constructor:  private NLog() { }  public static double e = Math.E; //2.71828...}

聲明空構造函數(shù)可阻止自動生成默認構造函數(shù)。注意,如果您不對構造函數(shù)使用訪問修飾符,則在默認情況下它仍為私有構造函數(shù)。但是,通常顯式地使用 private 修飾符來清楚地表明該類不能被實例化。
當沒有實例字段或?qū)嵗椒ǎㄈ?Math 類)時或者當調(diào)用方法以獲得類的實例時,私有構造函數(shù)可用于阻止創(chuàng)建類的實例。如果類中的所有方法都是靜態(tài)的,可考慮使整個類成為靜態(tài)的。

下面是使用私有構造函數(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

注意,如果您取消注釋該示例中的以下語句,它將生成一個錯誤,因為該構造函數(shù)受其保護級別的限制而不可訪問:

// Counter aCounter = new Counter();  // Error

靜態(tài)構造函數(shù)
靜態(tài)構造函數(shù)用于初始化任何靜態(tài)數(shù)據(jù),或用于執(zhí)行僅需執(zhí)行一次的特定操作。在創(chuàng)建第一個實例或引用任何靜態(tài)成員之前,將自動調(diào)用靜態(tài)構造函數(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)構造函數(shù)具有以下特點:

  • 靜態(tài)構造函數(shù)既沒有訪問修飾符,也沒有參數(shù)。
  • 在創(chuàng)建第一個實例或引用任何靜態(tài)成員之前,將自動調(diào)用靜態(tài)構造函數(shù)來初始化類。
  • 無法直接調(diào)用靜態(tài)構造函數(shù)。
  • 在程序中,用戶無法控制何時執(zhí)行靜態(tài)構造函數(shù)。

靜態(tài)構造函數(shù)的典型用途是:當類使用日志文件時,將使用這種構造函數(shù)向日志文件中寫入項。

靜態(tài)構造函數(shù)在為非托管代碼創(chuàng)建包裝類時也很有用,此時該構造函數(shù)可以調(diào)用 LoadLibrary 方法。
如果靜態(tài)構造函數(shù)引發(fā)異常,運行時將不會再次調(diào)用該構造函數(shù),并且在程序運行所在的應用程序域的生存期內(nèi),類型將保持未初始化。
在此示例中,類 Bus 有一個靜態(tài)構造函數(shù)。創(chuàng)建 Bus 的第一個實例(bus1)時,將調(diào)用該靜態(tài)構造函數(shù)來初始化該類。輸出示例驗證了即使創(chuàng)建 Bus 的兩個實例,該靜態(tài)構造函數(shù)也僅運行一次,并且在實例構造函數(shù)運行之前運行。

 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.   

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 罗定市| 广南县| 临漳县| 辽阳县| 宁都县| 大石桥市| 武邑县| 江达县| 颍上县| 乡城县| 大同市| 临朐县| 嘉峪关市| 临泽县| 鞍山市| 沂源县| 武定县| 新津县| 北海市| 河源市| 筠连县| 山东省| 孝昌县| 泽州县| 天水市| 周至县| 永安市| 疏附县| 周宁县| 故城县| 柘城县| 都匀市| 西城区| 化州市| 凤翔县| 班玛县| 眉山市| 永嘉县| 新建县| 阜康市| 鱼台县|