Static functions chỉ truy cập được static variables. Static functions tồn tại trước khi object được tạo.
Đặt static functions:
public static int getNum() {}
Ví dụ minh họa static functions:
Ví dụ
using System;
namespace Demo {
class StaticVar {
public static int num;
public void count() {
num++;
}
public static int getNum() {
return num;
}
}
class StaticTester {
static void Main(string[] args) {
StaticVar s = new StaticVar();
s.count();
s.count();
s.count();
Console.WriteLine("Variable num: {0}", StaticVar.getNum());
Console.ReadKey();
}
}
}
Kết quả
Variable num: 3