How to trim an array in .NET?

大城市里の小女人 提交于 2019-12-12 21:22:16

问题


Say I have an array

array<double>^ buffer = gcnew array<double>(100);

And I want a function that does something like:

void foo(array<double>^% buffer)
{
    Array::Resize(buffer, 10);
}

but that don't allocate and/or move &buffer[0] when you want to trim the array.


回答1:


.NET arrays are immutable in size once created. You can't trim it; you must reallocate and copy. So Array.Resize already does everything you need. Perhaps just ignore the elements at the end if you really don't want to do this.

Or; use a List<T>, which encapsulates an array, and does have TrimExcess(). In C# terms:

    var list = new List<int>(100);
    // prints 0/100
    Console.WriteLine("{0} / {1}", list.Count, list.Capacity);
    list.Add(1);
    list.Add(2);
    list.Add(3);
    // prints 3/100
    Console.WriteLine("{0} / {1}", list.Count, list.Capacity);
    list.TrimExcess();
    // prints 3/3
    Console.WriteLine("{0} / {1}", list.Count, list.Capacity);



回答2:


You cannot do this in .NET. Arrays in .NET are of fixed size once allocated; the only way you can change the size of an array is to re-allocate it (which is what Array.Resize does), and this will invariably change the location of the array in memory.



来源:https://stackoverflow.com/questions/1751345/how-to-trim-an-array-in-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!