我有一个特定的方法,偶尔会因 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)>) 的容量,并且在添加新元素之前将现有元素复制到新数组中。
有人能想到 AddRange 可以抛出此类异常的情况吗?
Edit:
回答有关 FindObjects() 方法的问题。它基本上看起来像这样:
List<MyObject> retObjs = new List<MyObject>();
foreach(MyObject obj in objectList)
{
if(someCondition)
retObj.Add(obj);
}