Generics cho phép viết code tái sử dụng với nhiều kiểu dữ liệu khác nhau mà vẫn đảm bảo an toàn kiểu (type safety) tại compile-time. Thay vì dùng object (mất type safety, boxing/unboxing), generics dùng tham số kiểu <T>.
5 tính năng chính
- Generic classes với ràng buộc (constraints):
class MyClass<T> where T : IComparable- cho phép gọi phương thức trên kiểu cụ thể. - Reflection trên kiểu generic: Lấy thông tin kiểu tại runtime với
typeof(List<int>),MethodInfo.GetGenericArguments(). - Tái sử dụng code, an toàn kiểu, hiệu năng: Tránh boxing/unboxing, giảm code trùng lặp, kiểm tra kiểu tại compile-time.
- Generic Collections: Namespace
System.Collections.Genericcung cấpList<T>,Dictionary<TKey,TValue>,HashSet<T>,Queue<T>,Stack<T>... thay thế các lớp non-generic cũ trongSystem.Collections. - Tự định nghĩa generic: Interface, class, method, delegate, event đều có thể generic.
Ví dụ: Generic Method
using System;
class Utility
{
// Generic method swap
public static void Swap<T>(ref T a, ref T b)
{
T temp = a; a = b; b = temp;
}
// Generic method với constraint
public static T Max<T>(T a, T b) where T : IComparable<T>
{
return a.CompareTo(b) > 0 ? a : b;
}
}
class Program
{
static void Main()
{
int x = 5, y = 10;
Utility.Swap(ref x, ref y);
Console.WriteLine($"Swap int: {x}, {y}"); // 10, 5
string s1 = "apple", s2 = "banana";
Console.WriteLine($"Max string: {Utility.Max(s1, s2)}"); // banana
}
}
Lợi ích so với non-generic
| Đặc điểm | Non-generic (object/ArrayList) | Generic (List<T>) |
|---|---|---|
| Type safety | Runtime error | Compile-time error |
| Boxing/Unboxing | Có (value types) | Không |
| Hiệu năng | Thấp hơn | Cao hơn |
| IntelliSense | Hạn chế | Hoàn chỉnh |