class Program
{
static void Main(string[] args)
{
//創(chuàng)建 一個(gè) 集合類 封裝
ListClass<int> myList = new ListClass<int>();
for (int i = 0; i < 10; i++)
{
myList.Add(i);
}
for (int i = 0; i < myList.Count; i++)
{
Console.WriteLine(myList[i]);
}
Console.ReadKey();
}
}
class ListClass<T>
{
private T[] arr; //字段县习;
private int count;
public int Count//屬性
{
get { return count; }
set { count = value; }
}
private int capactiy;
public int Capactiy
{
get { return capactiy; }
set { capactiy = value; }
}
//構(gòu)造函數(shù)
public ListClass()
{
arr = new T[] { };
}
public ListClass(int length)
{
if (length >= 0)
{
arr = new T[length];
}
else
{
Console.WriteLine("長(zhǎng)度不能小于零纯赎!");
}
}
//添加方法
public void Add(T str)
{
if (count == this.Capactiy)
{
if (count == 0)
{
arr = new T[4];
}
if (count == this.Capactiy && this.Count != 0)
{
T[] arrNew = new T[this.Capactiy * 2];
Array.Copy(arr, arrNew, this.Count);
arr = arrNew;
}
}
arr[count] = str;
this.Count++;
}
//設(shè)置索引器
public T this[int index]
{
get { return this.GetItem(index); }
set
{
if (index >= 0 && index < this.Capactiy)
{
arr[index] = value;
}
else
{
throw new Exception("索引產(chǎn)出范圍!");
}
}
}
private T GetItem(int index)
{
if (index >= 0 && index < this.Capactiy)
{
return arr[index];
}
else
{
throw new Exception("索引產(chǎn)出范圍屏富!");
}
}
//插入一個(gè)元素
public void Insert(int index, T item)
{
if (this.count + 1 > this.Capactiy)
{
T[] arrNew = new T[this.Capactiy * 2];//創(chuàng)建擴(kuò)容數(shù)組
Array.Copy(arr, arrNew, this.count);//把原來數(shù)組copy到擴(kuò)容后的數(shù)組趁俊;
arr = arrNew;
for (int i = 0; i < this.count; i++)
{
if (i >= index)
{
for (int j = this.count; j >= index; j--)
{
arr[j] = arr[j - 1];
}
arr[index] = item;
count++;
break;
}
}
}
else
{
for (int i = 0; i < this.count; i++)
{
if (i >= index)
{
for (int j = this.count; j >= index; j--)
{
arr[j] = arr[j - 1];
}
this.count++;
arr[index] = item;
break;
}
}
}
}
//指定下標(biāo)移除元素
public void RemoveAt(int index)
{
for (int i = 0; i < this.count; i++)
{
if (i == index)
{
for (int j = index; j < this.count; j++)
{
arr[j] = arr[j + 1];
}
this.count--;
break;
}
}
}
//指定元素尋找第一次出現(xiàn)的下標(biāo)
public int IndexOf(T str)
{
int index = -1;
for (int i = 0; i < arr.Length; i++)
{
if (arr[i].Equals(str))//判斷是否相等
{
index = i;
}
}
return index;
}
//反轉(zhuǎn)
public void Reverse()
{
T[] arrTemp = new T[this.count];
for (int i = 0; i < this.count; i++)
{
arrTemp[i] = arr[this.count - 1 - i];
}
arr = arrTemp;
}
}