gpt4 book ai didi

c# - LIST<> AddRange 抛出 ArgumentException

转载 作者:太空狗 更新时间:2023-10-29 17:34:40 29 4
gpt4 key购买 nike

我有一个特殊的方法,偶尔会因 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);
}

最佳答案

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

关于c# - LIST<> AddRange 抛出 ArgumentException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2593267/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com