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 日

1K+ 瀏覽

開啟你的 職業生涯

完成該課程獲得認證

開始
廣告位
© . All rights reserved.