C# 中的靜態成員函式是什麼?


靜態函式只能訪問靜態變數。靜態函式在物件建立之前就已經存在。

設定靜態函式如下 −

public static int getNum() {}

以下示例演示了靜態函式的使用 −

示例

 線上演示

using System;

namespace Demo {
   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();

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

輸出

Variable num: 3

更新於: 2020 年 6 月 20 日

556 次瀏覽

啟動您的 職業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.