Extension Method & Chaining Function

1️⃣ Extension Method

Để khai báo một extension method, cần lưu ý:

  • 📝 Phương thức mở rộng phải nằm trong static class.
  • ⚡ Phương thức mở rộng phải là static method.
  • 🔹 Parameter đầu tiên phải dùng từ khóa this kèm object mà phương thức muốn mở rộng.

Ví dụ: Mở rộng lớp string với method Print

static class ExtensionClass
{
    public static void Print(this string s, ConsoleColor color)
    {
        Console.ForegroundColor = color;
        Console.WriteLine(s);
    }
}

⚡ Thực thi

string s = "Hello World !";
s.Print(ConsoleColor.Yellow);

✅ Output: “Hello World !” màu vàng trên console


2️⃣ Chaining Function

Để viết chaining function, cần lưu ý:

  • 🔹 Method phải trả về chính class chứa nó.
  • ⚡ Cuối method cần return this; để có thể gọi tiếp method khác.

Ví dụ: JsonTemplateBuilder để append nhiều giá trị key-value

public class JsonTemplateBuilder
{
    private Dictionary<string, string> _options = new Dictionary<string, string>();

    public JsonTemplateBuilder Add(string key, string value)
    {
        if (!_options.ContainsKey(key))
            _options.Add(key, value);
        return this; // ⚡ Trả về class để có thể chaining
    }

    public string Build()
    {
        return $"{{{JsonConvert.SerializeObject(_options)}}}";
    }
}

⚡ Thực thi

var myString = new JsonTemplateBuilder()
                    .Add("timestamp", "UtcDateTime(@t)")
                    .Add("timestamp", "@m")
                    .Add("abc", "@bcd")
                    .Add("1", "@11")
                    .Add("2", "@22")
                    .Build();

Console.WriteLine(myString);
Console.ReadLine();

✅ Output: Chuỗi JSON với các key-value đã thêm, dễ dàng mở rộng bằng chaining.


🔑 Tóm tắt

  • Extension Method giúp thêm method mới vào class hiện có mà không cần kế thừa.
  • Chaining Function giúp gọi liên tiếp các method trên cùng một object, code gọn gàng, dễ đọc.