Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Virtual Functions (Hàm ảo) trong C#

Từ khóa virtual dùng để sửa đổi phương thức, property, indexer, event. Khi có hàm trong lớp cha muốn lớp con triển khai, dùng virtual function. Hàm ảo có thể triển khai khác nhau ở các lớp con, gọi được quyết định tại runtime.

Hàm ảo:

public virtual int area() { }

Ví dụ

using System;

namespace PolymorphismApplication {
    class Shape {
        protected int width, height;
        public Shape(int a = 0, int b = 0) {
            width = a;
            height = b;
        }
        public virtual int area() {
            Console.WriteLine("Lớp cha area:");
            return 0;
        }
    }
    class Rectangle : Shape {
        public Rectangle(int a = 0, int b = 0) : base(a, b) { }
        public override int area() {
            Console.WriteLine("Lớp Rectangle area");
            return (width * height);
        }
    }
    class Triangle : Shape {
        public Triangle(int a = 0, int b = 0) : base(a, b) { }
        public override int area() {
            Console.WriteLine("Lớp Triangle area:");
            return (width * height / 2);
        }
    }
    class Caller {
        public void CallArea(Shape sh) {
            int a = sh.area();
            Console.WriteLine("Diện tích: {0}", a);
        }
    }
    class Tester {
        static void Main(string[] args) {
            Caller c = new Caller();
            Rectangle r = new Rectangle(10, 7);
            Triangle t = new Triangle(10, 5);
            c.CallArea(r);
            c.CallArea(t);
            Console.ReadKey();
        }
    }
}