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

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

Interface (อินเทอร์เฟซ)

Interface เป็นคลาสที่ไม่มี Fields และไม่มีการนำเมธอดไปใช้งาน (Implementation) มันเพียงแต่ "ประกาศ" สมาชิกว่ามีอะไรบ้าง คลาสที่ Implement Interface จะต้องเป็นผู้เขียนโค้ดการทำงานจริง

Syntax ของ Interface

public interface IInterfaceName {
    // Interface members - มีแค่ Declaration
    void MyMethod();
    int MyProperty { get; set; }
    event EventHandler MyEvent;
}

Class (คลาส)

Class เป็นแม่แบบ (Blueprint) สำหรับชนิดข้อมูล กำหนดว่าอ็อบเจ็กต์ของคลาสนี้ประกอบด้วยอะไรบ้าง และสามารถทำอะไรได้บ้าง

Syntax ของ Class

public class ClassName {
    // Class members - มีทั้ง Declaration และ Implementation
    private int _field;
    
    public int MyProperty { get; set; }
    
    public void MyMethod() {
        // Implementation จริง
        Console.WriteLine("Hello!");
    }
}

ตารางเปรียบเทียบความแตกต่างหลัก

คุณสมบัติ Interface Class
Fields (ตัวแปรสมาชิก) ไม่สามารถมีได้ (C# 8.0+ สามารถมี static fields ได้) มีได้ (instance และ static)
Method Implementation ไม่มี (C# 8.0+ สามารถมี Default Implementation ได้) มี Implementation จริง
Constructor ไม่มี มีได้
Inheritance Implement ได้หลาย Interface (Multiple) สืบทอดได้เพียง 1 Class (Single)
Access Modifiers ทุกอย่างเป็น public โดยค่าเริ่มต้น ระบุได้ทุกประเภท
Instantiation ไม่สามารถ new ได้โดยตรง new ได้ (ถ้าไม่ใช่ abstract)
วัตถุประสงค์ กำหนด "สัญญา" (Contract) ว่าต้องทำอะไรได้บ้าง กำหนด "โครงสร้างและพฤติกรรม" จริง

ความสัมพันธ์ระหว่าง Interface และ Class

// Interface กำหนด "ว่าต้องทำอะไร"
public interface IDrivable {
    void Drive();
    void Stop();
}

// Class นำไป "ใช้งานจริง"
public class Car : IDrivable {
    public void Drive() {
        Console.WriteLine("Car is driving...");
    }
    
    public void Stop() {
        Console.WriteLine("Car stopped.");
    }
    
    // Class สามารถมีสมาชิกเพิ่มเติมได้
    public string Brand { get; set; }
    public int Speed { get; set; }
}

สรุป

  • Interface = "สัญญา" (What it does) - กำหนดข้อกำหนดที่ต้องปฏิบัติ
  • Class = "การนำไปใช้งาน" (How it does) - มีโค้ดจริงและสถานะ (State)
  • Class หนึ่งสามารถ Implement Interface หลายตัว แต่ สืบทอด Class ได้เพียงตัวเดียว