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.