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