C# 中的 static 關鍵字


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

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

以下是一個顯示 static 變數用法的示例 −

示例

 互動演示

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

更新於:2020-06-20

3K+ 次檢視

開啟你的 職業

透過完成課程獲得認證

開始
廣告