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

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

Dynamic Polymorphism (Runtime Polymorphism) - Method ที่เรียกใช้ถูกตัดสินใจที่ **Runtime** โดยใช้ virtual/override หรือ abstract

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

using System;

namespace PolymorphismApplication
{
    // Base Class
    class Shape
    {
        protected int Width, Height;
        
        public Shape(int w = 0, int h = 0)
        {
            Width = w; Height = h;
        }
        
        // Virtual Method - สามารถ Override ได้
        public virtual int Area()
        {
            Console.WriteLine("Parent class area:");
            return 0;
        }
    }
    
    // Derived Class: Rectangle
    class Rectangle : Shape
    {
        public Rectangle(int w = 0, int h = 0) : base(w, h) { }
        
        public override int Area()
        {
            Console.WriteLine("Rectangle class area:");
            return Width * Height;
        }
    }
    
    // Derived Class: Triangle
    class Triangle : Shape
    {
        public Triangle(int w = 0, int h = 0) : base(w, h) { }
        
        public override int Area()
        {
            Console.WriteLine("Triangle class area:");
            return Width * Height / 2;
        }
    }
    
    // Caller - ไม่รู้ Type จริง
    class Caller
    {
        public void CallArea(Shape shape)
        {
            int area = shape.Area(); // Runtime Binding
            Console.WriteLine("Area: {0}", area);
        }
    }
    
    class Tester
    {
        static void Main(string[] args)
        {
            Caller c = new Caller();
            c.CallArea(new Rectangle(10, 7)); // Area: 70
            c.CallArea(new Triangle(10, 5));  // Area: 25
            Console.ReadKey();
        }
    }
}

ผลลัพธ์

Rectangle class area:
Area: 70
Triangle class area:
Area: 25

Abstract Class Version

abstract class Shape
{
    public abstract int Area(); // บังคับ Override
}

class Circle : Shape
{
    public int Radius { get; set; }
    public override int Area() => (int)(Math.PI * Radius * Radius);
}

Static vs Dynamic Polymorphism

คุณสมบัติStatic (Compile-time)Dynamic (Runtime)
กลไกMethod OverloadingMethod Overriding
BindingEarly BindingLate Binding
Performanceเร็วกว่าช้ากว่า (v-table)
Flexibilityน้อยกว่ามากกว่า