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

更新於:20-Jun-2020

556 次瀏覽

開啟您的 職業

完成課程以獲得認證

開始吧
廣告
© . All rights reserved.