索引器必须以this关键字定义
public string this[int index]{
get { retur arr[index];}
set { arr[index] = value;}
}
class Program
{static void Main(string[] args)
{
MyArrayList<int> myL = new MyArrayList<int>(5);
myL[0] = 1;
myL[1] = 2;
myL[2] = 3;
myL[3] = 4;
myL[4] = 5;
//myL.Unshift(3);
//myL.Push(4);
//myL.Shift();
//myL.Pop();
myL.Splice(2,3,5);
for (int i = 0; i < myL.Len; i++) {
Console.WriteLine(myL[i]);
}
Console.ReadKey();
}
}
class MyArrayList<T>
{
T[] arr = null; //数组
T[] brr = null; //中间数组
int len = 0; //数组长度
//构造函数
public MyArrayList(int i)
{
len = i; //通过构造函数定义容器长度
arr = new T[len];
}
//数组长度的属性
public int Len
{
get { return len; }
}
//索引器
public T this[int index]
{
get { return arr[index]; }
set { arr[index] = value; }
}
//在数组首位添加一个新的元素
public void Unshift(T t) {
brr = new T[len];
brr = arr;
arr = new T[len + 1];
arr[0] = t;
for (int i = 0; i < len; i++) {
arr[i + 1] = brr[i];
}
len++;
brr = null;
}
//在数组尾部添加一个新的元素
public void Push(T t) {
brr = new T[len];
brr = arr;
arr = new T[len + 1];
arr[len] = t;
for (int i = 0; i < len; i++)
{
arr[i] = brr[i];
}
len++;
brr = null;
}
//删除首位的第一个元素并返回
public T[] Shift() {
brr = new T[len];
brr = arr;
arr = new T[len - 1];
for (int i = 0; i < len - 1; i++)
{
arr[i] = brr[i+1];
}
len--;
brr = null;
return arr;
}
//删除尾部最后一个元素并返回
public T[] Pop() {
brr = new T[len];
brr = arr;
arr = new T[len - 1];
for (int i = 0; i < len - 1; i++)
{
arr[i] = brr[i];
}
len--;
brr = null;
return arr;
}
//splice(开始添加或删除的下标,删除的个数,添加的元素)
public void Splice(params object[] a) {
int index = (int)a[0];
int count = (int)a[1];
T add = (T)a[2];
//Console.WriteLine("t = {0}", add);
brr = new T[len];
brr = arr;
arr = new T[len - count + 1];
//i是原来数组的索引,j是新数组的索引
for (int i = 0,j = 0; i < len; i++,j++)
{
if (j == index)
{
arr[j] = add;
i = i + count - 1;
}
else
{
arr[j] = brr[i];
}
}
len = len - count + 1;
brr = null;
}
}