如何在 .NET 中修剪数组?
假设我有一个数组
array<double>^ buffer = gcnew array<double>(100);
,我想要一个执行以下操作的函数:
void foo(array<double>^% buffer)
{
Array::Resize(buffer, 10);
}
但是当您想要修剪数组时,它不会分配和/或移动 &buffer[0] 。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
.NET 数组一旦创建,大小就不可变。您无法修剪它;您必须重新分配和复制。所以 Array.Resize 已经完成了您需要的一切。如果您确实不想这样做,也许可以忽略最后的元素。
或者;使用
List
,它封装一个数组,并且确实有TrimExcess()
。用 C# 术语来说:.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 haveTrimExcess()
. In C# terms:您无法在 .NET 中执行此操作。 .NET 中的数组一旦分配就具有固定大小;更改数组大小的唯一方法是重新分配它(这就是 Array.Resize 所做的),这将不可避免地更改数组在内存中的位置。
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.
最近的 C#/.NET Core 版本附带了一种新类型 -
Span
- 它本质上是现有数组的“视图”。Spans 几乎可以被处理像数组一样,您可以通过 foreach 等对其进行迭代。
它们的发明就是为了这个目的 - 切片/修剪/操作数组而不分配新数组。但是您必须重写 API 才能使用
Span
数据类型(或者,在所有数组切片/重新切片完成后,只需在最后调用ToArray()
即可仍然分配一个新数组,但仅在所有工作完成后)https://learn.microsoft.com/en-us/dotnet/api/system.span-1?view=net-6.0
The recent C#/.NET Core versions come with a new type -
Span<T>
- which is essentially a "view" into an existing array.Spans can be treated almost like arrays, you can iterate it via
foreach
etc.They were invented just for this very purpose - to slice/trim/manipulate arrays without allocating new arrays. BUT you will have to rewrite your API to work with
Span
datatype (or, after all the array slicing/reslicing is complete, just callToArray()
at the end which will still allocate a new array, but only once all the work is finished)https://learn.microsoft.com/en-us/dotnet/api/system.span-1?view=net-6.0