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

Generics trong C#


Generics cho phép viết class/method làm việc với bất kỳ kiểu dữ liệu nào.

Viết spec cho class/method với tham số thay thế kiểu dữ liệu. Compiler sinh code xử lý kiểu cụ thể khi gặp constructor/gọi hàm.

Lợi ích Generics:

  • Tái sử dụng code, type safety, performance.
  • Tạo generic collection classes. Thư viện .NET có generic collections trong System.Collections.Generic thay cho System.Collections.
  • Tự tạo generic interfaces, classes, methods, events, delegates.
  • Generic classes constrained để truy cập method trên kiểu đặc định.
  • Lấy thông tin kiểu tại runtime qua reflection.