C# 中 static 關鍵字


我們可以使用 static 關鍵字將類成員定義為靜態。當我們宣告一個類的成員為靜態時,這意味著無論建立了多少個類的物件,靜態成員只存在一個副本。

關鍵字 static 意味著一個類的成員只存在一個例項。靜態變數用於定義常量,因為無需建立類的例項即可透過呼叫類來檢索其值。

以下示例展示了靜態變數的用法 −

示例

 Live Demo

using System;

namespace StaticVarApplication {
   class StaticVar {
      public static int num;

      public void count() {
         num++;
      }

      public int getNum() {
         return num;
      }
   }

   class StaticTester {
      static void Main(string[] args) {
         StaticVar s1 = new StaticVar();
         StaticVar s2 = new StaticVar();

         s1.count();
         s1.count();
         s1.count();

         s2.count();
         s2.count();
         s2.count();

         Console.WriteLine("Variable num for s1: {0}", s1.getNum());
         Console.WriteLine("Variable num for s2: {0}", s2.getNum());
         Console.ReadKey();
      }
   }
}

輸出

Variable num for s1: 6
Variable num for s2: 6

更新日期: 20-6 月-2020

3K+ 瀏覽量

開啟你事業

完成課程獲得認證

開始學習
廣告
© . All rights reserved.