我有一个特定的方法,它偶尔会与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()应该根据需要自动调整自身大小:
如果新计数(当前计数加上集合大小)大于容量,则通过自动重新分配内部数组以容纳新元素来增加List<( <(T>)>)的容量,并在添加新元素之前将现有元素复制到新数组中。
有人能想到AddRange可以抛出这种异常的情况吗?
编辑:
以回答有关FindObjects()方法的问题。基本上是这样的:
List<MyObject> retObjs = new List<MyObject>();
foreach(MyObject obj in objectList)
{
if(someCondition)
retObj.Add(obj);
}发布于 2010-04-07 14:31:00
您是否试图从多个线程中更新相同的列表?可能会引起问题..。对于多个作者来说,List<T>并不安全。
发布于 2010-04-07 14:32:59
老实说,我不确定,但是为什么不直接删除列表初始化中的size声明呢?
List`<MyType>` list = new List`<MyType>`https://stackoverflow.com/questions/2593267
复制相似问题