Biến Static
Thuộc về class, không phải instance. Chia sẻ bởi tất cả instance. Dùng cho hằng số, counter, shared state.
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("s1.num: {0}", s1.GetNum()); // 6
Console.WriteLine("s2.num: {0}", s2.GetNum()); // 6
Console.ReadKey();
}
}
}
Kết quả
s1.num: 6 s2.num: 6
Biến Instance (Class Variables / Fields)
Thuộc về từng object, private để encapsulation, truy cập qua property/method.
using System;
namespace BoxApplication
{
class Box
{
private double length;
private double breadth;
private double height;
public void SetLength(double len) { length = len; }
public void SetBreadth(double bre) { breadth = bre; }
public void SetHeight(double hei) { height = hei; }
public double GetVolume() { return length * breadth * height; }
}
class Boxtester
{
static void Main(string[] args)
{
Box box1 = new Box();
box1.SetLength(6); box1.SetBreadth(7); box1.SetHeight(5);
Console.WriteLine("Thể tích Box1: {0}", box1.GetVolume()); // 210
Box box2 = new Box();
box2.SetLength(12); box2.SetBreadth(13); box2.SetHeight(10);
Console.WriteLine("Thể tích Box2: {0}", box2.GetVolume()); // 1560
Console.ReadKey();
}
}
}
So sánh
| Đặc điểm | Static | Instance |
|---|---|---|
| Lưu trữ | Một bản cho cả class | Mỗi object một bản |
| Truy cập | ClassName.StaticField | obj.InstanceField |
| Khởi tạo | Static constructor / inline | Instance constructor |
| Thread safety | Cần lock nếu ghi | Tách biệt per instance |