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

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

Class = Blueprint/Template (แม่แบบ) สำหรับสร้าง Object

Object = Instance (ตัวจริง) ที่สร้างจาก Class

Analogy

  • Class = ใบเสร็จแบบฟอร์ม (Template)
  • Object = ใบเสร็จที่กรอกข้อมูลแล้ว (Instance)

ตัวอย่าง: Box Class และ Box Objects

using System;

namespace BoxApplication
{
    class Box
    {
        // Member Variables (Fields) - Private ตาม Encapsulation
        private double length;
        private double breadth;
        private double height;
        
        // Member Functions (Methods) - Public Interface
        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;
    }
    
    class BoxTester
    {
        static void Main(string[] args)
        {
            // สร้าง Object 2 ตัวจาก Class เดียว
            Box box1 = new Box(); // box1 คือ Object/Instance
            Box box2 = new Box(); // box2 คือ Object/Instance อีกตัว
            
            // ใช้ Dot Operator (.) เข้าถึง Members
            box1.SetLength(6.0);
            box1.SetBreadth(7.0);
            box1.SetHeight(5.0);
            
            box2.SetLength(12.0);
            box2.SetBreadth(13.0);
            box2.SetHeight(10.0);
            
            double volume;
            
            volume = box1.GetVolume();
            Console.WriteLine("Volume of Box1: {0}", volume); // 210
            
            volume = box2.GetVolume();
            Console.WriteLine("Volume of Box2: {0}", volume); // 1560
            
            Console.ReadKey();
        }
    }
}

ผลลัพธ์

Volume of Box1: 210
Volume of Box2: 1560

สมาชิกของ Class (Members)

ประเภทตัวอย่าง
Fields (Data)length, breadth, height
Methods (Behavior)SetLength, GetVolume
PropertiesLength { get; set; }
EventsOnVolumeChanged
ConstructorsBox()
Destructors~Box()
Indexersthis[int i]
Operatorsoperator +
Nested Typesclass Inner { }

สรุป

  • Class = Definition (Compile-time Concept)
  • Object = Instance (Runtime Entity)
  • 1 Class สร้าง Object ได้หลายตัว (Multiple Instances)
  • แต่ละ Object มี State (Fields) แยกกัน
  • Method ใช้ร่วมกัน (Shared Code)