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

ความแตกต่างระหว่าง Object และ Class ใน C#

Class vs Object ใน C#

ความสัมพันธ์พื้นฐานของ OOP: **Class = แม่แบบ (Blueprint), Object = อินสแตนซ์/วัตถุจริง (Instance)**

Class (คลาส) - แม่แบบ

  • นิยามโครงสร้าง: Fields (ข้อมูล), Properties, Methods (พฤติกรรม), Events
  • ไม่ใช้หน่วยความจำสำหรับข้อมูล (แค่ metadata)
  • เป็น Reference Type
  • สร้างได้ไม่จำกัดจำนวน Object

Object (ออบเจ็กต์/อินสแตนซ์) - วัตถุจริง

  • สร้างจาก Class ด้วย new
  • มีหน่วยความจำของตัวเอง (heap)
  • มีค่า state (field values) แยกต่างหาก
  • เข้าถึงสมาชิกผ่าน dot operator .

ตัวอย่างครบถ้วน


using System;

namespace BoxApplication
{
    // Class Definition
    class Box
    {
        // Fields (ข้อมูล) - private encapsulation
        private double length;
        private double breadth;
        private double height;

        // Methods (พฤติกรรม)
        public void SetLength(double len) => length = len;
        public void SetBreadth(double bre) => breadth = bre;
        public void SetHeight(double hei) => height = hei;

        public double GetVolume() => length * breadth * height;
    }

    // Tester Class
    class BoxTester
    {
        static void Main(string[] args)
        {
            // สร้าง Object (Instantiation) 2 ตัวจาก Class เดียว
            Box box1 = new Box(); // Object 1
            Box box2 = new Box(); // Object 2 - แยกต่างหาก

            // ใช้ Object เรียก Method ตั้งค่า
            box1.SetLength(6.0);
            box1.SetBreadth(7.0);
            box1.SetHeight(5.0);

            box2.SetLength(12.0);
            box2.SetBreadth(13.0);
            box2.SetHeight(10.0);

            // ใช้ Object เรียก Method คำนวณ
            double volume1 = box1.GetVolume(); // 210
            double volume2 = box2.GetVolume(); // 1560

            Console.WriteLine($"Volume of Box1: {volume1}");
            Console.WriteLine($"Volume of Box2: {volume2}");

            // แสดงว่าเป็น object ต่างกัน
            Console.WriteLine($"Same reference? {ReferenceEquals(box1, box2)}"); // False
        }
    }
}

ผลลัพธ์


Volume of Box1: 210
Volume of Box2: 1560
Same reference? False

แผนภาพความสัมพันธ์


┌─────────────────────────────────────┐
│           CLASS: Box                │
│  ┌─────────────────────────────┐    │
│  │ Fields: length, breadth,    │    │
│  │         height (private)    │    │
│  ├─────────────────────────────┤    │
│  │ Methods: SetLength(),       │    │
│  │          SetBreadth(),      │    │
│  │          SetHeight(),       │    │
│  │          GetVolume()        │    │
│  └─────────────────────────────┘    │
└─────────────────────────────────────┘
                │
                │ new Box()
                ▼
    ┌─────────────────┐     ┌─────────────────┐
    │  OBJECT: box1   │     │  OBJECT: box2   │
    │ length = 6.0    │     │ length = 12.0   │
    │ breadth = 7.0   │     │ breadth = 13.0  │
    │ height = 5.0    │     │ height = 10.0   │
    │ Volume = 210    │     │ Volume = 1560   │
    └─────────────────┘     └─────────────────┘

Reference Semantics


Box box1 = new Box();
Box box2 = box1; // box2 ชี้ไป object เดียวกับ box1

box1.SetLength(10);
Console.WriteLine(box2.GetVolume()); // เปลี่ยนตาม! เพราะชี้ object เดียวกัน

// ต้องการ copy จริง ต้อง implement Clone/ICloneable หรือ copy manual
Box box3 = new Box();
box3.SetLength(box1.length); // copy field ทีละตัว

Struct vs Class - Value vs Reference

ลักษณะClass (Reference Type)Struct (Value Type)
เก็บในHeapStack (โดยทั่วไป)
AssignmentCopy referenceCopy value (deep copy)
Nullได้ไม่ได้ (ถ้าไม่ใช่ Nullable)
Inheritanceได้ไม่ได้ (แต่ implement interface ได้)
ใช้เมื่อมี identity, mutable, largeเล็ก, immutable, ค่าตัวเลข

Static Members - ร่วมกันระหว่าง Object ทุกตัว


class Box
{
    static int Count = 0; // Shared
    
    public Box() => Count++;
    
    public static int GetCount() => Count;
}

var b1 = new Box();
var b2 = new Box();
Console.WriteLine(Box.GetCount()); // 2 - ร่วมกัน