C#中泛型在Class上的實現
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
GenericArray intArray = new GenericArray(5);//實例化一個泛型的數組
for (int i = 0; i < 5; i++)
{
intArray.SetItem(i, i * 5);
Console.WriteLine(intArray.GetItem(i));
}
Console.WriteLine();
//同樣的方法用於字符串數組:
GenericArray charArray = new GenericArray(5);
for (int i = 0; i < 5; i++)
{
charArray.SetItem(i, (char)(i +97));
Console.WriteLine(charArray.GetItem(i));
}
}
public class GenericArray
{
private T[] array;
//構造函數
public GenericArray(int size)
{
array = new T[size];
}
//讀取方法
public T GetItem(int index)
{
return array[index];
}
//賦值方法
public void SetItem(int index, T value)
{
array[index] = value;
}
}
}
}