當您需要一個通用、可重複使用的方法來處理不同的資料類型時,泛型就非常有用。以下是一個簡單的C#泛型使用的例子:
using System;
class Program
{
static void Main()
{
// 宣告一個字串型態的泛型List
MyList<string> stringList = new MyList<string>();
stringList.Add("Apple");
stringList.Add("Banana");
stringList.Add("Cherry");
// 宣告一個整數型態的泛型List
MyList<int> intList = new MyList<int>();
intList.Add(10);
intList.Add(20);
intList.Add(30);
// 顯示字串型態的泛型List中所有的資料
Console.WriteLine("字串型態的泛型List:");
foreach (string str in stringList)
{
Console.WriteLine(str);
}
// 顯示整數型態的泛型List中所有的資料
Console.WriteLine("整數型態的泛型List:");
foreach (int num in intList)
{
Console.WriteLine(num);
}
Console.ReadLine();
}
}
class MyList<T>
{
private T[] items = new T[5];
private int count = 0;
// 新增資料到泛型List中
public void Add(T item)
{
if (count + 1 < items.Length)
{
items[count++] = item;
}
}
// 支援foreach迴圈的GetEnumerator()方法
public IEnumerator<T> GetEnumerator()
{
for (int i = 0; i < count; i++)
{
yield return items[i];
}
}
}
這個例子展示了如何使用C#的泛型List來存儲不同類型的資料,並在程式中輕鬆地操作和存取這些資料。注意,泛型類型的名稱通常以大寫字母T開始,T代表型態參數。在上面的例子中,T可以是任何類型,因為它是泛型。