我用ILSpy反编译了 mscorlib 库,并注意到该List.Clear
方法在Array.Clear(this._items, 0, this._size)
内部使用。
// System.Collections.Generic.List<T>
/// <summary>Removes all elements from the <see cref="T:System.Collections.Generic.List`1" />.</summary>
public void Clear()
{
if (this._size > 0)
{
Array.Clear(this._items, 0, this._size);
this._size = 0;
}
this._version++;
}
接下来,此Array.Clear
方法将所有数组元素设置为零、false 或 null,如其描述的那样。也在List.RemoveRange
用Array.Clear
方法。
// System.Array
/// <summary>Sets a range of elements in the <see cref="T:System.Array" /> to zero, to false, or to null, depending on the element type.</summary>
/// <param name="array">The <see cref="T:System.Array" /> whose elements need to be cleared.</param>
/// <param name="index">The starting index of the range of elements to clear.</param>
/// <param name="length">The number of elements to clear.</param>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="array" /> is null.</exception>
/// <exception cref="T:System.IndexOutOfRangeException">
/// <paramref name="index" /> is less than the lower bound of <paramref name="array" />.-or-<paramref name="length" /> is less than zero.-or-The sum of <paramref name="index" /> and <paramref name="length" /> is greater than the size of the <see cref="T:System.Array" />.</exception>
/// <filterpriority>1</filterpriority>
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success), SecuritySafeCritical]
[MethodImpl(MethodImplOptions.InternalCall)]
public static extern void Clear(Array array, int index, int length);
是否可以忽略Array.Clear(this._items, 0, this._size)
值类型的第一个代码清单中的方法调用?我认为没有必要。我对吗?
这个问题不仅适用于 List,而且适用于其他通用集合。