如何證明僅為靜態類建立了物件的一個例項?


這裡在示例中建立一個靜態的 Demo 類並且聲明瞭一個靜態變數 count。

在這裡 count 變數被當作全域性變數處理。所以它在示例中持續增加,因為僅建立了該類的例項。

示例

static class Demo{
   public static int count;
   static Demo(){
      System.Console.WriteLine("Static Constuctor called");
   }
}
class Program{
   static void Main(){
      Demo.count++;
      Demo.count++;
      System.Console.WriteLine(Demo.count);
      Console.ReadKey();
   }
}

輸出

Static Constuctor called
2

更新於: 04-8-2020

167 次瀏覽

開啟你的 職業生涯

透過完成本課程獲得認證

開始
廣告
© . All rights reserved.