有下面的方法和属性
1,Capacity获取容量大小
2,Add()方法添加元素
3,Insert()方法插入元素
4,[index]访问元素(索引器)
5,Count属性访问元素个数
6,RemoveAt()方法移除指定位置的元素
7,IndexOf()方法取得一个元素所在列表中的案引位置
LastindexOf()上面的方法是从前往后搜索,这个是从后往前搜索,搜索到满足条件的就
停止
上面的两个方法,如果没有找到指定元素就返回-18,Sort()对列表中是元素进行从小到大排序索引器:通过[index]这种形式去访问数据,就是索引器
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace MyList
{
internal class MyList<T>
{
private T[] array = new T[0];
private int count = 0;
public int Capacity
{
get { return array.Length; }
}
public int Count
{
get { return count; }
}
public void Add(T item)
{
if (array.Length == 0)
{
array = new T[4];
}
if (array.Length == count)
{
T[] temp = new T[array.Length * 2];
for (int i = 0; i < array.Length; i++)
{
temp[i] = array[i];
}
array = temp;
}
array[count] = item;
count++;
}
public T this[int index]
{
get
{
if ((index < 0) || (index > count - 1))
{
Console.WriteLine("数组索引超出");
System.Environment.Exit(0);
}
return array[index];
}
set { array[index] = value; }
}
public void insert(int index, T item)
{
if ((index < 0) || (index > count - 1))
{
Console.WriteLine("数组索引超出");
System.Environment.Exit(0);
}
for (int i = count - 1; i > index - 1; i--)
{
array[i + 1] = array[i];
}
array[index] = item;
count++;
}
public void removeAt(int index)
{
if ((index < 0) || (index > count - 1))
{
Console.WriteLine("数组索引超出");
System.Environment.Exit(0);
}
for (int i = index + 1; i < count; i++)
{
array[i - 1] = array[1];
}
count--;
}
public int IndexOf(T item)
{
int index = -1;
for (int i = 0; i < count; i++)
{
if (item.Equals(array[i]))
{
index = i;
break;
}
}
return index;
}
public int LastindexOf(T item)
{
int index = -1;
for (int i = count - 1; i >= 0; i--)
{
if (item.Equals(array[i]))
{
index = i;
break;
}
}
return index;
}
public T[] Sort()
{
dynamic c;
for (int i = 0; i < count; i++)
{
for ( int j = i; j <count-i-1; j++)
{
if (Convert.ToInt32( array[j] )>Convert.ToInt32( array[j+1]))
{
c = array[j];
array[j] = array[j+1];
array[j + 1] = c;
}
}
}
return array ;
}
}
}