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

WBOY
WBOY 转载
2023-09-04 14:17:08 734浏览

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

Declare a member function as static. Such functions can access only static variables. The static functions exist even before the object is created.

A static class cannot be instantiated and can only contain static members.

Static methods is set using static keyword −

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

以上就是C# 中的静态方法与非静态方法的详细内容,更多请关注php中文网其它相关文章!

声明:本文转载于:tutorialspoint,如有侵犯,请联系admin@php.cn删除