C# 中 static 关键字
我们可以使用 static 关键字将类成员定义为静态。当我们声明一个类的成员为静态时,这意味着无论创建了多少个类的对象,静态成员只存在一个副本。
关键字 static 意味着一个类的成员只存在一个实例。静态变量用于定义常量,因为无需创建类的实例即可通过调用类来检索其值。
以下示例展示了静态变量的用法 −
示例
using System;
namespace StaticVarApplication {
class StaticVar {
public static int num;
public void count() {
num++;
}
public int getNum() {
return num;
}
}
class StaticTester {
static void Main(string[] args) {
StaticVar s1 = new StaticVar();
StaticVar s2 = new StaticVar();
s1.count();
s1.count();
s1.count();
s2.count();
s2.count();
s2.count();
Console.WriteLine("Variable num for s1: {0}", s1.getNum());
Console.WriteLine("Variable num for s2: {0}", s2.getNum());
Console.ReadKey();
}
}
}输出
Variable num for s1: 6 Variable num for s2: 6
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP