【jq】c#零基础学习之路(5)自己编写简单的Mylist<T>
1 public class MyList<T> where T : IComparable 2 { 3 4 private T[] array; 5 private int count; 6 public MyList(int size) 7 { 8 if (size >= 0) 9 { 10 array = new T[size]; 11 } 12 13 } 14 public MyList() 15 { 16 array = new T[0]; 17 } 18 public int Capacity 19 { 20 get 21 { 22 return array.Length; 23 } 24 } 25 public int Count 26 { 27 get { return count; } 28 } 29 public void Add(T a) 30 { 31 if (Count == Capacity) 32 { 33 if (Capacity == 0) 34 { 35 array = new T[4]; 36 } 37 else 38 { 39 var newarray = new T[Capacity * 2]; 40 Array.Copy(array, newarray, count); 41 array = newarray; 42 } 43 } 44 array[count] = a; 45 count++; 46 } 47 public T GetItem(int index) 48 { 49 if (index >= 0 && index <= count - 1) 50 { 51 return array[index]; 52 } 53 else 54 { 55 throw new Exception("超出索引"); 56 } 57 } 58 public T this[int index] 59 { 60 get 61 { 62 return GetItem(index); 63 } 64 set 65 { 66 67 if (index >= 0 && index <= count - 1) 68 { 69 array[index] = value; 70 } 71 else 72 { 73 throw new Exception("超出索引"); 74 } 75 } 76 } 77 public void Insert(int a, T t) 78 { 79 if (a >= 0 && a <= Count - 1) 80 { 81 if (count == Capacity) 82 { 83 var newarray = new T[Capacity * 2]; 84 Array.Copy(array, newarray, count); 85 array = newarray; 86 } 87 else 88 { 89 for (int i = count - 1; i >= a; i--) 90 { 91 array[i + 1] = array[i]; 92 } 93 array[a] = t; 94 count++; 95 } 96 } 97 } 98 public void RemoveAt(int a) 99 { 100 if (a >= 0 && a <= Count - 1) 101 { 102 for (int i = a + 1; i <= count - 1; i++) 103 { 104 array[i - 1] = array[i]; 105 } 106 count--; 107 } 108 } 109 public int IndexOf(T t) 110 { 111 for (int i = 0; i <= count - 1; i++) 112 { 113 if (array[i].Equals(t)) 114 { 115 return i; 116 } 117 } 118 return -1; 119 } 120 public int LastIndexOf(T t) 121 { 122 for (int i = count - 1; i >= 0; i--) 123 { 124 if (array[i].Equals(t)) 125 { 126 return i; 127 } 128 } 129 return -1; 130 } 131 public void Sort() 132 { 133 for (int j = 0; j < count - 1; j++) 134 { 135 136 137 for (int i = 0; i < count - 1 - j; i++) 138 { 139 if (array[i].CompareTo(array[i + 1]) > 0) 140 { 141 T tamp = array[i]; 142 array[i] = array[i + 1]; 143 array[i + 1] = tamp; 144 } 145 } 146 } 147 } 148 }
泛型列表