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

Method Hiding (Shadowing) ใน C# คืออะไร

Method Hiding หรือที่รู้จักในชื่อ Shadowing คือเทคนิคที่คลาสลูก (Child Class) สร้างเมธอดใหม่ที่มีชื่อและลายเซ็นเหมือนกับเมธอดในคลาสแม่ (Parent Class) โดยไม่ใช้คีย์เวิร์ด override แต่ใช้คีย์เวิร์ด new แทน

คุณสมบัติหลัก

  • เมธอดในคลาสแม่ยังคงอยู่และเข้าถึงได้ผ่านอ็อบเจ็กต์ของคลาสแม่
  • คลาสลูกมีเวอร์ชันของเมธอดตัวเอง
  • ใช้คีย์เวิร์ด new เพื่อบอกคอมไพเลอร์ว่าเป็นการซ่อน (hiding) โดยเจตนา
  • ไม่ใช่ Polymorphism จริง (ไม่มี Dynamic Dispatch)

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

using System;

class Demo {
    public class Parent {
        public string GetInfo() {
            return "This is Parent Class!";
        }
    }
    
    public class Child : Parent {
        // ใช้ new เพื่อซ่อนเมธอดของ Parent
        public new string GetInfo() {
            return "This is Child Class!";
        }
    }
    
    static void Main(String[] args) {
        Child child = new Child();
        Console.WriteLine(child.GetInfo());  // เรียกเมธอดของ Child
        
        // ยังสามารถเข้าถึงเมธอด Parent ได้ผ่าน Casting
        Parent parent = child;
        Console.WriteLine(parent.GetInfo()); // เรียกเมธอดของ Parent
    }
}

ผลลัพธ์

This is Child Class!
This is Parent Class!

Method Hiding vs Method Overriding

คุณสมบัติ Method Hiding (new) Method Overriding (override)
คีย์เวิร์ด new override (ต้องมี virtual ใน Base)
Polymorphism ไม่ใช่ (Static Binding) เป็น (Dynamic Binding)
การเข้าถึง Base Method ผ่าน Casting หรือ base.Method() ผ่าน base.Method()
Runtime Behavior ขึ้นอยู่กับ Type ของตัวแปรอ้างอิง ขึ้นอยู่กับ Type ของอ็อบเจ็กต์จริง

เมื่อไหร่ควรใช้ Method Hiding?

  • เมื่อต้องการเปลี่ยนพฤติกรรมเมธอดโดยไม่ส่งผลต่อโค้ดที่ใช้ Base Class
  • เมื่อไม่สามารถแก้ไข Base Class ให้เป็น virtual ได้ (เช่น Library ของบุคคลที่สาม)
  • เมื่อต้องการ "แทนที่" การทำงานเดิมอย่างสมบูรณ์ ไม่ใช่ขยายต่อ

⚠️ ข้อควรระวัง

ถ้าไม่ใส่ new จะได้ Warning: 'Child.GetInfo()' hides inherited member 'Parent.GetInfo()'. Use the new keyword if hiding was intended.