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
廣告
資料結構
計算機網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言
C++
C#
MongoDB
MySQL
JavaScript
PHP