我有一个特定的方法,偶尔会出现ArgumentException错误:
Destination array was not long enough. Check destIndex and length, and the array's lower bounds.:
at System.Array.Copy(Array sourceArray, Int32 sourceIndex, Array destinationArray, Int32 destinationIndex, Int32 length, Boolean reliable)
at System.Collections.Generic.List`1.CopyTo(T[] array, Int32 arrayIndex)
at System.Collections.Generic.List`1.InsertRange(Int32 index, IEnumerable`1 collection)
at System.Collections.Generic.List`1.AddRange(IEnumerable`1 collection)
导致崩溃的代码大致如下:
List<MyType> objects = new List<MyType>(100);
objects = FindObjects(someParam);
objects.AddRange(FindObjects(someOtherParam);
根据MSDN的说明,List<>.AddRange()应该会自动根据需要调整大小:
如果新的Count(当前Count加上集合的大小)大于Capacity,则List<(Of <(T>)>)的容量将通过自动重新分配内部数组以容纳新元素来增加,并且在添加新元素之前将现有元素复制到新数组中。
有人能想到AddRange可能抛出这种类型的异常的情况吗?
编辑:
针对FindObjects()方法的问题,它基本上看起来像这样:
List<MyObject> retObjs = new List<MyObject>();
foreach(MyObject obj in objectList)
{
if(someCondition)
retObj.Add(obj);
}
FindObjects
返回什么?另外,为什么你在初始化objects
后立即在下一行重新赋值它? - user203570this._items [this._size ++] = item;
代码...导致后一个线程崩溃。当Jon在下面的答案中说List<T>
不是线程安全的时,这就是List<T>
无法处理的问题之一。 - Nick Craver