1 using System; 2 3 namespace _01_调试和错误排查 4 { 5 class MyList<T> 6 { 7 private T[] data = new T[4]; 8 private int count = 0; 9 10 //索引器 11 public T this[int index] 12 { 13 get 14 { 15 if (index < 0 || index >= count) 16 { 17 throw new ArgumentOutOfRangeException("索引参数超出范围"); 18 } 19 return data[index]; 20 } 21 set 22 { 23 data[index] = value; 24 } 25 } 26 27 //获取容量 28 public int Capacity 29 { 30 get 31 { 32 return data.Length; 33 } 34 } 35 36 //获取长度 37 public int Count 38 { 39 get 40 { 41 return count; 42 } 43 } 44 45 //添加元数 46 public void Add(T value) 47 { 48 if (data.Length <= 0) 49 { 50 data = new T[4]; 51 } 52 if (data.Length == count) 53 { 54 T[] _arr = new T[count * 2]; 55 for (int i = 0; i < data.Length; i++) 56 { 57 _arr[i] = data[i]; 58 } 59 data = _arr; 60 } 61 data[count] = value; 62 count++; 63 } 64 65 //插入 66 public void insert(int index, T item) 67 { 68 if (index < 0 || index > count) 69 { 70 throw new ArgumentOutOfRangeException("索引参数超出范围"); 71 } 72 for (int i = count - 1; i > index - 1; i--) 73 { 74 data[i + 1] = data[i]; 75 } 76 data[index] = item; 77 count++; 78 } 79 80 //移除元素 81 public void RemoveAt(int index) 82 { 83 if (index < 0 || index > count) 84 { 85 throw new ArgumentOutOfRangeException("索引参数超出范围"); 86 } 87 for (int i = index; i < count; i++) 88 { 89 data[i] = data[i + 1]; 90 } 91 count--; 92 } 93 94 //从前往后查找元素索引 95 public int IndexOf(T item) 96 { 97 int temp = -1; 98 for (int i = 0; i < count; i++) 99 { 100 if (item.Equals(data[i])) 101 { 102 temp = i; 103 break; 104 } 105 } 106 return temp; 107 } 108 109 //从后往前查找元素索引 110 public int LastIndexOf(T item) 111 { 112 int temp = -1; 113 for (int i = count - 1; i >= 0; i--) 114 { 115 if (item.Equals(data[i])) 116 { 117 temp = i; 118 break; 119 } 120 } 121 return temp; 122 } 123 124 //排序 125 public void Sort() 126 { 127 Array.Sort(data, 0, count); 128 } 129 } 130 131 public class Test 132 { 133 static void Main() 134 { 135 MyList<int> myList = new MyList<int>(); 136 137 //测试 138 myList.Add(11); 139 myList.Add(2); 140 myList.Add(32); 141 myList.Add(14); 142 myList.Add(43); 143 myList.Add(11); 144 myList.Add(6); 145 myList.Add(57); 146 myList.Add(81); 147 myList.Add(9); 148 myList.Add(100); 149 myList[2] = 1; 150 myList.insert(2, 24); 151 myList.RemoveAt(7); 152 Console.WriteLine(myList.IndexOf(11)); 153 Console.WriteLine(myList.LastIndexOf(11)); 154 Console.WriteLine("容量" + myList.Capacity); 155 Console.WriteLine("长度" + myList.Count); 156 157 for (int i = 0; i < myList.Count; i++) 158 { 159 Console.Write(myList[i] + " "); 160 } 161 myList.Sort(); 162 Console.WriteLine(); 163 for (int i = 0; i < myList.Count; i++) 164 { 165 Console.Write(myList[i] + " "); 166 } 167 } 168 } 169 }