1、在Class上的实现
实现相同类型,方法应用与不同数据类型上面,提高代码的利用率
示例:
1 static void Main(string[] args) 2 { 3 //int型显示 4 MyGenericArray<int> intarray = new MyGenericArray<int>(5); 5 for (int c = 0; c < 5; c++) 6 { 7 intarray.SetItem(c, c * 5); 8 } 9 for (int c = 0; c < 5; c++) 10 { 11 Console.Write(intarray.GetItem(c) + " "); 12 } 13 Console.WriteLine(); 14 15 //char型显示 16 MyGenericArray<char> chararray = new MyGenericArray<char>(5); 17 for (int c = 0; c < 5; c++) 18 { 19 chararray.SetItem(c, (char)(c + 97)); 20 } 21 for (int c = 0; c < 5; c++) 22 { 23 Console.Write(chararray.GetItem(c) + " "); 24 } 25 Console.ReadLine(); 26 } 27 28 public class MyGenericArray<T> 29 { 30 private T[] array; 31 32 public MyGenericArray(int size) 33 { 34 array = new T[size + 1]; 35 } 36 37 public T GetItem(int index) 38 { 39 return array[index]; 40 } 41 42 public void SetItem(int index, T value) 43 { 44 array[index] = value; 45 } 46 }