如何修剪在.NET中的数组? [英] How to trim an array in .NET?

查看:153
本文介绍了如何修剪在.NET中的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个数组

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);
}

但不分配和/或移动和放大器;缓冲区[0]当你要修剪的阵列

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

推荐答案

.NET数组是不可改变的大小创建一次。您不可以修剪;你必须重新分配并复制。因此, Array.Resize 已做了你所需要的一切。也许只是忽略末尾的元素,如果你真的不希望这样做。

.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;使用名单,其中,T&GT; ,其中的封装的数组,确实的有无 TrimExcess( )。在C#方面:

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);

这篇关于如何修剪在.NET中的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆