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

Các tính năng của Generic (Chung) trong C#

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

  1. 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ể.
  2. Reflection trên kiểu generic: Lấy thông tin kiểu tại runtime với typeof(List<int>), MethodInfo.GetGenericArguments().
  3. 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.
  4. Generic Collections: Namespace System.Collections.Generic cung cấp List<T>, Dictionary<TKey,TValue>, HashSet<T>, Queue<T>, Stack<T>... thay thế các lớp non-generic cũ trong System.Collections.
  5. 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ểmNon-generic (object/ArrayList)Generic (List<T>)
Type safetyRuntime errorCompile-time error
Boxing/UnboxingCó (value types)Không
Hiệu năngThấp hơnCao hơn
IntelliSenseHạn chếHoàn chỉnh