我試圖使用Array
增加數組的大小.Copy C#內置static
方法。 代碼如下:Array.Copy異常
public class MyClass
{
private int Capacity { get; set; }
private int Size { get; set; }
private int[] Nodes { get; set; }
public MyClass()
{
Capacity = 5;
Size = 0;
Nodes = new int[Capacity];
}
public void EnlargeIfNeeded()
{
if (Size == Capacity)
{
Capacity = 2 * Capacity;
Array.Copy(Nodes, Nodes, Capacity);
}
}
}
它拋出以下異常,當方法EnlargeIfNeeded()
被調用:
system.argument.exception: Source array was not long enough. Check srcIndex and length, and the array's lower bound
是否確定使用以下?我的單元測試通過OK,現在:
public void EnlargeIfNeeded()
{
if (Size == Capacity)
{
Capacity = 2 * Capacity;
var dest = new int[Capacity];
Array.Copy(Nodes, dest, Capacity/2);
Nodes = dest;
}
}
你期望加倍場'Capacity'影響陣列'Nodes'的實際容量? 'Array.Copy'當然不會這樣做。 – dasblinkenlight
是的,我最終的目的是將陣列容量加倍。 –
我建議你仔細閱讀'Array.Copy'的文檔。你目前沒有正確使用它。您可能想使用'Nodes = Array.Resize(Nodes,Capacity)'來代替。但爲什麼你基本上重新創建'List'? –