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

Runtime Polymorphism ใน C# คืออะไร

Runtime Polymorphism (Dynamic Polymorphism / Late Binding) - เมธอดที่เรียกใช้ถูกตัดสินใจที่ **Runtime** ตาม Object Type จริง

กลไก 2 แบบ

  1. Abstract Classes - Abstract Methods บังคับ Override
  2. Virtual Functions - Virtual Methods สามารถ Override ได้

1. Abstract Classes

using System;

namespace PolymorphismApplication
{
    // Abstract Class - ไม่สามารถ Instantiate เองได้
    abstract class Shape
    {
        public abstract int Area(); // Abstract Method - ไม่มี Body
    }
    
    class Rectangle : Shape
    {
        private int length, width;
        
        public Rectangle(int a = 0, int b = 0)
        {
            length = a; width = b;
        }
        
        // ต้อง Override
        public override int Area()
        {
            Console.WriteLine("Rectangle class area:");
            return width * length;
        }
    }
    
    class RectangleTester
    {
        static void Main(string[] args)
        {
            Shape shape = new Rectangle(10, 7); // Upcast
            double area = shape.Area(); // Runtime: เรียก Rectangle.Area()
            Console.WriteLine("Area: {0}", area);
            Console.ReadKey();
        }
    }
}

ผลลัพธ์

Rectangle class area:
Area: 70

2. Virtual Functions

using System;

public class Animal
{
    public virtual void MakeSound()
    {
        Console.WriteLine("Some sound");
    }
}

public class Dog : Animal
{
    public override void MakeSound()
    {
        Console.WriteLine("Woof!");
    }
}

public class Cat : Animal
{
    public override void MakeSound()
    {
        Console.WriteLine("Meow!");
    }
}

class Program
{
    static void Main()
    {
        Animal[] animals = { new Dog(), new Cat(), new Animal() };
        
        foreach (var a in animals)
        {
            a.MakeSound(); // Runtime Polymorphism
        }
    }
}

ผลลัพธ์

Woof!
Meow!
Some sound

สรุป: Abstract vs Virtual

คุณสมบัติAbstract MethodVirtual Method
Body ใน Baseไม่มี (ต้อง Override)มี (Default Implementation)
Overrideบังคับเลือกได้
Classต้องเป็น Abstract ClassClass ธรรมดาได้
Sealed Overrideได้ (sealed override)ได้ (sealed override)