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

แนวคิดของ Class ใน C#


Class เป็น Type สำคัญที่สุดใน C# คล้าย Blueprint (แผนผัง) สำหรับ Objects ใน Problem Domain เป็น Template สร้าง Objects กำหนดโครงสร้างและพฤติกรรมที่ Object ทุกตัวจาก Class นี้จะแบ่งปัน อย่างง่าย: Class คือ Cookie Cutter, Objects คือ Cookies

Class ให้ Encapsulation (การห่อหุ้ม) แนวคิดสำคัญใน OOP: รวม Data และ Operations ที่ทำงานกับ Data ไว้ที่เดียว ให้ API เรียบง่ายแก่ผู้ใช้ และซ่อนรายละเอียดที่ไม่เกี่ยวข้อง

สร้าง Class ด้วย Keyword class:

// User.cs
public class User
{
    private string name;
    private int salary;
    public void Promote() => salary += 1000;
}

Class User แทนผู้ใช้ Encapsulate 2 Fields: name, salary มี Method Promote() เพิ่มเงินเดือน

Access Modifier ควบคุม Visibility ของ Class (5 ระดับ):

Modifierคำอธิบาย
publicเข้าถึงได้ไม่จำกัด
protectedเข้าถึงได้ใน Derived Classes
internalเข้าถึงได้ใน Assembly เดียวกัน
protected internalเข้าถึงได้ใน Assembly หรือ Derived Classes
privateเข้าถึงไม่ได้จากภายนอก

สร้าง Instance ด้วย new Keyword: new คำนวณ Memory จัดสรร และคืน Reference (Pointer) ไปยัง Object ใหม่ Reference เก็บไว้ใน Variable ด้านซ้าย =

var alice = new User();
var bob = new User();

Naming Convention: PascalCase (StringBuilder, UserController) ไม่บังคับให้ชื่อไฟล์ตรง Class Name แต่มักนิยมทำ

Constructors

Constructor ใช้ Initialize ข้อมูล Class ตอนสร้าง Object:

public class User
{
    private string name;
    private int salary;
    public User(string name, int salary)
    {
        this.name = name;
        this.salary = salary;
    }
    public void Promote() => salary += 1000;
}

สร้าง Instance พร้อมค่าเริ่มต้น:

var alice = new User("Alice", 50000);
var bob = new User("Bob", 45000);

สามารถมี Multiple Constructors ได้ (Constructor Overloading):

public User(string name)
{
    this.name = name;
    this.salary = 50000; // Default
}

ตัวอย่างโค้ดครบ

using System;

class Program
{
    static void Main()
    {
        var alice = new User();
        alice.Print();

        var bob = new User();
        bob.Print();

        var chris = new User("Chris", 50000);
        chris.Print();

        var debs = new User("Debs", 45000);
        debs.Print();

        var scott = new User("Scott");
        scott.Print();
    }
}

public class User
{
    private string name;
    private int salary;

    public User() { }
    public User(string name) { this.name = name; this.salary = 50000; }
    public User(string name, int salary) { this.name = name; this.salary = salary; }

    public void Promote() => salary += 1000;
    public void Print() => Console.WriteLine($"{name}: {salary}");
}

ผลลัพธ์