C# 中的 static 关键字
我们可以使用 static 关键字将类成员定义为 static。当我们将类的成员声明为 static 时,这意味着无论创建了多少类的对象,static 成员都只有一个副本。
关键字 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