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

Làm code tái sử dụng (Reusable) trong C#

Code reusable trong C#: Interface, Abstract class, Generic, Dependency Injection, Extension Method, Design Patterns.

1. Interface - Contract chung

public interface IShape
{
    double Area();
    void Draw();
}

// Triển khai đa hình
public class Circle : IShape
{
    public double Radius { get; set; }
    public double Area() => Math.PI * Radius * Radius;
    public void Draw() => Console.WriteLine("Drawing circle");
}

public class Rectangle : IShape
{
    public double Width { get; set; }
    public double Height { get; set; }
    public double Area() => Width * Height;
    public void Draw() => Console.WriteLine("Drawing rectangle");
}

// Sử dụng - Polymorphism
void ProcessShape(IShape shape)
{
    shape.Draw();
    Console.WriteLine($"Area: {shape.Area()}");
}

2. Generic - Type-safe reuse

public interface IRepository
{
    T GetById(int id);
    void Add(T entity);
    void Remove(T entity);
}

public class UserRepository : IRepository { ... }
public class ProductRepository : IRepository { ... }

3. Extension Method - Mở rộng type có sẵn

public static class StringExtensions
{
    public static bool IsNullOrEmpty(this string s) 
        => string.IsNullOrEmpty(s);
    
    public static string Truncate(this string s, int len)
        => s.Length <= len ? s : s[..len] + "...";
}

// Dùng như method của string
"hello".Truncate(3); // "hel..."

4. Dependency Injection (DI) - Loose coupling

// Interface
public interface IEmailService { void Send(string to, string body); }

// Implementation
public class SmtpEmailService : IEmailService { ... }
public class MockEmailService : IEmailService { ... }

// Consumer - không biết implementation cụ thể
public class UserService
{
    private readonly IEmailService _email;
    public UserService(IEmailService email) => _email = email; // Injected
    
    public void Register(string email) => _email.Send(email, "Welcome!");
}

5. Design Patterns

  • Strategy: Thuật toán có thể thay thế
  • Factory: Tạo object trừu tượng
  • Decorator: Thêm hành vi động
  • Repository: Abstract data access

Nguyên tắc SOLID: Single Responsibility, Open/Closed, Liskov Substitution, Interface Segregation, Dependency Inversion - nền tảng của code reusable.