C# 中的靜態與非靜態方法


將成員函式宣告為靜態。此類函式只能訪問靜態變數。靜態函式甚至可在建立物件之前就存在。

靜態類不能被例項化,且只能包含靜態成員。

透過使用靜態關鍵字設定靜態方法 -

public static int getNum() {
   return num;
}

以下示例演示靜態與非靜態方法的使用 -

示例

using System;

namespace StaticVarApplication {
   class StaticVar {
      public static int num;

      public void count() {
         num++;
      }

      public static int getNum() {
         return num;
      }
   }

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

         s.count();
         s.count();
         s.count();
         s.count();
         s.count();
         s.count();

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

更新於: 2020 年 6 月 21 日

1 千次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告