2011-05-20 100 views
13

在什麼情況下System.Collections.Generic.List中的項目不會被成功刪除?在什麼情況下System.Collections.Generic.List中的項不會被成功刪除?

http://msdn.microsoft.com/en-us/library/cd666k3e.aspx

true,如果項目被成功取出; 否則爲false。如果 List(Of T)中找不到項目,此方法也會返回false。

他們這樣說的方式讓我覺得有可能對List(Of T)中找到的項目執行Remove操作實際上可能會失敗,因此會出現此問題。

+1

我的理解是失敗的,如果該項目不存在,但我也有興趣爲它怎麼可能會失敗......好問題:) – Jaymz 2011-05-20 10:19:00

回答

5

綜觀反射的System.Collections.Generic.List源,它會出現在集合中未找到該項目確實是唯一的出路對於Remove來返回false。上述

int index = this.IndexOf(item); 
if (index >= 0) 
{ 
    this.RemoveAt(index); 
    return true; 
} 
return false; 
4

是的它可以,如果您試圖刪除不在列表中的項目 - 它被歸類爲失敗並返回false以顯示沒有任何內容被刪除。

如果你真的想刪除其他代碼,這可能很有用。

更新:如果你的類實現了IEquality,並拋出一個異常,代碼讓拋出發生,因爲它沒有機會返回。

加上其他人張貼反映的來源,返回false只有當它找不到一個項目。

更新:繼續他人的來源。如果你看看IndexOf方法鏈,你會發現它歸結爲平等,並沒有什麼特別的。

List.Remove:

public bool Remove(T item) 
{ 
    int num = this.IndexOf(item); 
    if (num >= 0) 
    { 
     this.RemoveAt(num); 
     return true; 
    } 
    return false; 
} 

List.IndexOf:

public int IndexOf(T item) 
{ 
    return Array.IndexOf<T>(this._items, item, 0, this._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")); 
    } 
    return EqualityComparer<T>.Default.IndexOf(array, value, startIndex, count); 
} 

EqualityComparer.IndexOf:

internal virtual int IndexOf(T[] array, T value, int startIndex, int count) 
{ 
    int num = startIndex + count; 
    for (int i = startIndex; i < num; i++) 
    { 
     if (this.Equals(array[i], value)) 
     { 
      return i; 
     } 
    } 
    return -1; 
} 

所有的ILSpy代碼,沒有感謝紅門:-)

+6

MSDN文檔引用了狀態,如果在列表中找不到該項目,則會返回false,以及如果未成功刪除該項目,則返回** – Jaymz 2011-05-20 10:18:21

+0

+ 1提到例外情況 – sehe 2011-05-20 10:29:32

4
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] 
public bool Remove(T item) 
{ 
    int index = this.IndexOf(item); 
    if (index >= 0) 
    { 
     this.RemoveAt(index); 
     return true; 
    } 
    return false; 
} 

代碼經由反射器。只有當它不在集合中時纔會被刪除。我猜文檔/語言差異。

相關問題