c# – LIST <> AddRange throwing ArgumentException

前端之家收集整理的这篇文章主要介绍了c# – LIST <> AddRange throwing ArgumentException前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个特殊的方法偶尔会用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()应根据需要自动调整大小:

If the new Count (the current Count plus the size of the collection) will be greater than Capacity,the capacity of the List<(Of <(T>)>) is increased by automatically reallocating the internal array to accommodate the new elements,and the existing elements are copied to the new array before the new elements are added.

有人会想到AddRange可能会抛出这种异常的情况吗?

编辑:

回答有关FindObjects()方法的问题.它基本上看起来像这样:

List<MyObject> retObjs = new List<MyObject>();

foreach(MyObject obj in objectList)
{
   if(someCondition)
       retObj.Add(obj);
}

解决方法

您是否尝试从多个线程更新相同的列表?这可能会导致问题…列表< T>对于多个作家来说是不安全的.

猜你在找的C#相关文章