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.