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