共用方式為


泛型類別和方法

泛型會將類型參數的概念引入 .NET。 泛型可讓您設計延遲一或多個型別參數規格的類別和方法,直到您在程式代碼中使用 類別或方法為止。 例如,藉由使用泛型型別參數 T,您可以撰寫一個類別,讓其他用戶端程式代碼可以使用,而不會產生運行時間轉換或 Boxing 作業的成本或風險,如下所示:

// Declare the generic class.
public class GenericList<T>
{
    public void Add(T item) { }
}

public class ExampleClass { }

class TestGenericList
{
    static void Main()
    {
        // Create a list of type int.
        GenericList<int> list1 = new();
        list1.Add(1);

        // Create a list of type string.
        GenericList<string> list2 = new();
        list2.Add("");

        // Create a list of type ExampleClass.
        GenericList<ExampleClass> list3 = new();
        list3.Add(new ExampleClass());
    }
}

泛型類別和方法會以非泛型對應項目無法的方式結合可重複使用性、型別安全性和效率。 泛型型別參數會在編譯期間取代為類型自變數。 在上述範例中,編譯程式會將 T 取代為 int。 泛型最常與集合和在其上作的方法搭配使用。 命名空間 System.Collections.Generic 包含數個泛型集合類別。 不建議使用非泛型集合,例如 ArrayList ,而且僅供相容性之用維護。 如需詳細資訊,請參閱 .NET中的 泛型。

您也可以建立自定義泛型類型和方法,以提供您自己的一般化解決方案和設計模式,這些模式是類型安全且有效率。 下列程式代碼範例示範示範用途的簡單泛型連結清單類別。 (在大部分情況下,您應該使用 List<T> .NET 提供的 類別,而不是建立您自己的類別。類型參數 T 用於數個位置,其中一般會使用具體類型來指出儲存在清單中之專案的類型:

  • 做為方法中 AddHead 方法參數的類型。
  • 作為巢狀 Data 類別中 Node 屬性的傳回型別。
  • 做為巢狀類別中私用成員 data 的類型。

T 可供巢狀 Node 類別使用。 當 GenericList<T> 具現化為具體類型時,例如作為 GenericList<int>,每次出現的 T 都會被替換為 int

// Type parameter T in angle brackets.
public class GenericList<T>
{
    // The nested class is also generic, and
    // holds a data item of type T.
    private class Node(T t)
    {
        // T as property type.
        public T Data { get; set; } = t;

        public Node? Next { get; set; }
    }

    // First item in the linked list
    private Node? head;

    // T as parameter type.
    public void AddHead(T t)
    {
        Node n = new(t);
        n.Next = head;
        head = n;
    }

    // T in method return type.
    public IEnumerator<T> GetEnumerator()
    {
        Node? current = head;

        while (current is not null)
        {
            yield return current.Data;
            current = current.Next;
        }
    }
}

下列程式代碼範例示範用戶端程式代碼如何使用泛型 GenericList<T> 類別來建立整數清單。 如果您變更類型自變數,下列程式代碼會建立字串清單或任何其他自訂類型:

// A generic list of int.
GenericList<int> list = new();

// Add ten int values.
for (int x = 0; x < 10; x++)
{
    list.AddHead(x);
}

// Write them to the console.
foreach (int i in list)
{
    Console.WriteLine(i);
}

Console.WriteLine("Done");

備註

泛型型別不限於類別。 上述範例使用 class 類型,但您可以定義泛型 interfacestruct 類型,包括 record 類型。

泛型概觀

  • 使用泛型型別將程式代碼重複使用、類型安全性和效能最大化。
  • 最常見的泛型用法是建立集合類別。
  • .NET 類別庫包含命名空間中的 System.Collections.Generic 數個泛型集合類別。 盡可能使用泛型集合,而不是ArrayList 命名空間中的類別如System.Collections
  • 您可以建立自己的泛型介面、類別、方法、事件和委派。
  • 泛型類別可以設置限制,以在特定資料類型上啟用方法的存取。
  • 您可以在執行時使用反射取得泛型數據類型中所使用的類型資訊。

C# 語言規格

如需詳細資訊,請參閱<C# 語言規格>。

另請參閱