List<T>類
所屬命名空間:System.Collections.Generic
publicclassList<T> : IList<T>,ICollection<T>, IEnumerable<T>, IList,ICollection, IEnumerable
List<T>類是 ArrayList 類的泛型等效類。該類使用大小可按需動態增加的數組實現 IList<T> 泛型接口。
泛型的好處: 它爲使用c#語言編寫面向對象程序增加了極大的效力和靈活性。不會強行對值類型進行裝箱和拆箱,或對引用類型進行向下強制類型轉換,所以性能得到提高。
性能注意事項:在決定使用IList<T> 還是使用ArrayList類(兩者具有類似的功能)時,記住IList<T> 類在大多數情況下執行得更好並且是類型安全的。如果對IList<T> 類的類型 T 使用引用類型,則兩個類的行爲是完全相同的。但是,如果對類型 T 使用值類型,則需要考慮實現和裝箱問題。
用微軟的話講:“添加到ArrayList 中的任何引用或值類型都將隱式地向上強制轉換爲Object。如果項是值類型,則必須在將其添加到列表中時進行裝箱操作,在檢索時進行取消裝箱操作。強制轉換以及裝箱和取消裝箱操作都會降低性能;在必須對大型集合進行循環訪問的情況下,裝箱和取消裝箱的影響非常明顯。”
常用的操作List<T>的方法(屬性)
Capatcity 屬性獲取容量的大小
Count 屬性訪問元素的個數
Add(T item); 添加元素
Insert(int index,T item); 插入元素
[index] 訪問元素
RemoveAt(int index); 移除指定下標的元素
Remove(T item); 移除指定元素
IndexOf(T item) ;從下標0開始搜索指定的元素,並返回第一個匹配到的元素下標,沒有找到就返回-1
LastIndexOf(T item);與上面相反從後面開始索引,返回最後一個匹配到的元素下標,沒有找到就返回-1
Sort();對列表的元素從小到大的排序
自定義ArrayList
class ArrayDemo<T>
{
T[] arr;
private int count = 0;
private int capcity = 0;
/// <summary>
/// 返回數組中存儲的元素個數
/// </summary>
public int Count
{
get
{
return count;
}
}
/// <summary>
/// 返回數組的容量,分配內存空間是有關係
/// </summary>
public int Capcity
{
get { return capcity; }
}
public ArrayDemo(int capcity = 0)
{
this.capcity = capcity;
arr = new T[capcity < 0 ? 0 : capcity];
count = 0;
}
/// <summary>
/// 在數組的尾部添加一個新的元素
/// 例如:第一個添加就在數組的0下標,第二個添加就在數組的1下標的位置
/// </summary>
/// <param name="value"></param>
public void Add(T value)
{
//當count==capcity的時候就表示原始容量已經滿了
//擴大容量=capcity*2;
if (capcity == 0)
{
capcity = 4;
arr = new T[capcity];
}
else if (capcity != 0 && count == capcity)
{
capcity = capcity * 2;
T[] brr = arr;
arr = new T[capcity];
Array.Copy(brr, arr, count);
}
arr[count++] = value;
}
/// <summary>
/// 刪除指定下標的元素
/// </summary>
/// <param name="index"></param>
public void RemoveAt(int index)
{
if (index > count - 1)
{
Console.WriteLine("刪除錯誤:數組下標越界");
}
else
{
for (var i = index; i < count - 1; i++)
{
arr[i] = arr[i + 1];
}
arr[count - 1] = default(T);//將最後一個置爲默認值
count--;
}
}
/// <summary>
/// 刪除第一個在數組中檢索到的T類型的value元素
/// </summary>
/// <param name="value"></param>
public void Remove(T value)
{
for (var i = 0; i < count; i++)
{
if (value.Equals(arr[i]))
{
RemoveAt(i);
break;
}
}
}
/// <summary>
/// (索引器)通過下標返回指定下表的元素
/// </summary>
/// <param name="index">下標</param>
/// <returns>返回指定下標的元素,如果下標不存在就報錯</returns>
public T this[int index]
{
get
{
if (index < count && index >= 0)
return arr[index];
throw new System.IndexOutOfRangeException();
}
}
/// <summary>
/// 從數組首位開始檢索,並返回該元素第一次檢索到的下標,否則返回-1
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public int IndexOf(T value)
{
for (var i = 0; i < count; i++)
{
if (value.Equals(arr[i]))
{
return i;
}
}
return -1;
}
}
索引器(Indexer)
允許一個對象可以像數組一樣被索引。
當您爲類定義一個索引器時,該類的行爲就會像一個 虛擬數組(virtual array) 一樣。
您可以使用數組訪問運算符([ ])來訪問該類的實例。
索引器(Indexer)可被重載。
索引器聲明的時候也可帶有多個參數,且每個參數可以是不同的類型。
public T this[int index]
{
get{
if (index >= 0 && index < count)
{
return arr[index];
}
throw new System.IndexOutOfRangeException();
}
}