Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

Const vs Static vs Readonly ใน C#

Const

Constant fields คือ ฟิลด์ที่แก้ไขไม่ได้ ตอนประกาศต้องกำหนดค่าเลย

const int a = 5;

Static

ถ้า static modifier ใช้กับคลาส จะไม่สามารถสร้างอินสแตนซ์ด้วย new ได้ ใช้ static ได้กับเมธอด พร็อพเพอร์ตี้ คลาส คอนสตรัคเตอร์ ฯลฯ

static int a = 10;

Readonly

Readonly field เริ่มต้นตอนประกาศ หรือตั้งค่าใน constructor ได้

ตัวอย่าง readonly เริ่มต้นใน constructor

class Demo { 
    readonly int a; 
    public Demo() { a = 5; } 
}