Extension Methods là các phương thức static, nhưng được gọi như thể chúng là phương thức instance (thể hiện) của kiểu được mở rộng. Với Extension Methods, bạn có thể thêm phương thức vào các kiểu hiện có mà không cần tạo kiểu dẫn xuất, biên dịch lại, hay sửa đổi kiểu gốc.
Cú pháp
- Phải định nghĩa trong
static class - Phương thức phải
static - Tham số đầu tiên dùng từ khóa
thistheo sau là kiểu cần mở rộng
Ví dụ
using System;
namespace ExtensionMethodDemo
{
// Lớp static chứa extension methods
public static class StringExtensions
{
// Extension method: chuyển string thành int
public static int ToInt(this string str)
{
return Int32.Parse(str);
}
// Extension method khác: kiểm tra palindrome
public static bool IsPalindrome(this string str)
{
if (string.IsNullOrEmpty(str)) return true;
int left = 0, right = str.Length - 1;
while (left < right)
{
if (char.ToLower(str[left]) != char.ToLower(str[right]))
return false;
left++; right--;
}
return true;
}
}
class Program
{
static void Main(string[] args)
{
string str1 = "565";
int n = str1.ToInt(); // Gọi như method của string
Console.WriteLine("Kết quả: {0}", n);
string text = "Madam";
Console.WriteLine("{0} là palindrome? {1}", text, text.IsPalindrome());
Console.ReadLine();
}
}
}
Kết quả
Kết quả: 565 Madam là palindrome? True
Lưu ý quan trọng
- Extension method không thể truy cập thành viên private của kiểu mở rộng
- Nếu kiểu đã có method trùng tên, method instance được ưu tiên
- Cần
usingnamespace chứa extension class để sử dụng - Thường dùng cho: LINQ (
Where, Select, OrderBy), helper methods cho string, collection, v.v.