C# 中的静态方法与非静态方法

csharpprogrammingserver side programming更新于 2025/9/25 0:37:17

将成员函数声明为静态函数。此类函数只能访问静态变量。静态函数甚至在对象创建之前就已存在。

静态类无法实例化,并且只能包含静态成员。

使用 static 关键字设置静态方法 −

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();
      }
   }
}

相关文章