C#中的List(T)類型代表T類的列表,該類型位於 System.Collections.Generic命名空間,提供了按位置索引獲取對象的方法,並且列表支持搜索、排序等其它操作。本文重點介紹List(T)中的兩個方法:Contains(T)和IndexOf(T),特別的,T為自定義類類型。
(1)List(T).Contains(T)方法
該方法用於檢測某個T對象是否存在於List(T)對象中,List(T).Contains(T)方法繼承自ICollection(T).Contains(T),並對其進行了實現。首先看.net中該方法對應的代碼
// Contains returns true if the specified element is in the List. // It does a linear, O(n) search. Equality is determined by calling // item.Equals(). // public bool Contains(T item) { if ((Object) item == null) { for(int i=0; i<_size; i++) if ((Object) _items[i] == null) return true; return false; } else { EqualityComparer<T> c = EqualityComparer<T>.Default; for(int i=0; i<_size; i++) { if (c.Equals(_items[i], item)) return true; } return false; } }
通過該方法的實現代碼可以看出:1,該方法支持待檢測對象T為null,且當List(T)中含有null時,返回true,否則返回false;2,該方法使用EqualityComparer(T).Default比較器來比較兩個對象的相等性。而對於自定義的類型T,若該類實現了IEquatable(T)接口(即實現了Equals(T item)方法),則EqualityComparer(T).Default比較器就是調用的該方法進行的相等性比較。而若是該類未實現該接口,則會引用C#中Object.Equals(object obj)方法進行相等性測試,而對於引用類型,只有在兩個變量引用同一個實例(即實例在內存中的地址相等)時才會返回true。
(2)List(T).IndexOf(T)方法
該方法從List(T)中搜索特定的對象,並返回列表中第一個等於該對象的索引位置(以0為開始),當列表中不含有該對象時,返回-1。List(T).IndexOf(T)方法繼承自IList(T).IndexOf(T),並對其進行了實現。首先看.net中該方法對應的代碼:
// Returns the index of the first occurrence of a given value in a range of // this list. The list is searched forwards from beginning to end. // The elements of the list are compared to the given value using the // Object.Equals method. // // This method uses the Array.IndexOf method to perform the // search. // public int IndexOf(T item) { Contract.Ensures(Contract.Result<int>() >= -1); Contract.Ensures(Contract.Result<int>() < Count); return Array.IndexOf(_items, item, 0, _size); }
其中,所調用的Array類中IndexOf方法實現為:
public static int IndexOf<T>(T[] array, T value, int startIndex, int count) { if (array==null) { throw new ArgumentNullException("array"); } if (startIndex < 0 || startIndex > array.Length ) { throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_Index")); } if (count < 0 || count > array.Length - startIndex) { throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_Count")); } Contract.Ensures(Contract.Result<int>() < array.Length); Contract.EndContractBlock(); return EqualityComparer<T>.Default.IndexOf(array, value, startIndex, count); }
通過該方法的實現代碼可以看出:1,該方法借助了Array類的Index()方法進行了功能實現;2,同樣的,該方法使用EqualityComparer(T).Default比較器來比較兩個對象的相等性。此規則與Contains(T)方法類似