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

Trừu tượng hóa (Abstraction) trong C#

Abstraction (trừu tượng) - ẩn chi tiết triển khai, chỉ công khai interface cần thiết. Trong C# đạt được qua abstract class và interface.

Abstract Class

  • Chứa method abstract (chưa triển khai) và method concrete (đã triển khai)
  • Không thể khởi tạo trực tiếp
  • Class con bắt buộc override method abstract
  • Hỗ trợ single inheritance

Interface

  • Chỉ chứa signature (C# 8+: default implementation)
  • Class có thể implement nhiều interface
  • Không có state (field)
  • Contract (hợp đồng) thuần túy

Ví dụ Abstract Class

using System;

namespace Demo
{
    abstract class Shape
    {
        // Abstract method - bắt buộc override
        public abstract double Area();
        
        // Virtual method - có thể override
        public virtual void Display()
        {
            Console.WriteLine($"Diện tích: {Area():F2}");
        }
        
        // Concrete method - dùng chung
        public void PrintType() => Console.WriteLine($"Shape: {GetType().Name}");
    }
    
    class Rectangle : Shape
    {
        public double Width { get; set; }
        public double Height { get; set; }
        
        public Rectangle(double w, double h) { Width = w; Height = h; }
        
        public override double Area() => Width * Height;
    }
    
    class Circle : Shape
    {
        public double Radius { get; set; }
        public Circle(double r) { Radius = r; }
        
        public override double Area() => Math.PI * Radius * Radius;
    }
    
    class Program
    {
        static void Main()
        {
            Shape[] shapes = { new Rectangle(5, 3), new Circle(2) };
            
            foreach (var s in shapes)
            {
                s.PrintType();
                s.Display();
                Console.WriteLine();
            }
        }
    }
}

Kết quả đầu ra

Shape: Rectangle
Diện tích: 15.00

Shape: Circle
Diện tích: 12.57

Quy tắc quan trọng

  • Không thể new AbstractClass()
  • Method abstract không có body, không có private
  • Class sealed không thể kế thừa, abstract class không thể sealed
  • C# 8+: Interface có thể có default implementation