创建数组并调整它们的大小
假设我想创建一个包含 20 个元素的数组,所有元素均设置为默认值(假设为 0),
但是稍后,在运行时期间,我可能想要调整数组的大小。我可能会把它做得更大,以支持 30 个元素。这 10 个新元素的默认值为 0。
或者我可能想让我的数组更小,只有 5 个。所以我删除了数组最后 15 个元素的完整存在。
谢谢。
Lets say I want to create an array with 20 elements all set to a default value (let's say, 0)
But later, during runtime, I might want to resize the array. I might make it larger, to support 30 elements. The 10 new elements will have the default value of 0.
Or I might want to make my array smaller, to just 5. So I delete the complete the existence of the last 15 elements of the array.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
ReDim Preserve 会做到这一点,如果数组是在模块级别声明的,则引用它的任何代码都不会丢失引用。不过,我确实相信这是 vb 特有的,而且还会造成性能损失,因为这也会创建数组的副本。
我还没有检查过,但我怀疑上面描述的 user274204 方法可能是执行此操作的符合 CLR 的方法。 。
公开课 Form1
结束课
ReDim Preserve will do it, and if the array were declared at the module level, any code referencing it will not lose the reference. I do believe this is specific to vb, however, and there is also a performance penalty, in that this, too, is creating a copy of the array.
I haven't checked, but I suspect the method user274204 describes above is probably the CLR-compliant way to do this . .
Public Class Form1
End Class
一旦创建了数组(或任何其他对象),就不可能调整其大小。
您可以使用 System.Array.Resize(ref T[], int) 获得类似的效果。然而,这实际上会创建一个新数组,其中复制了相关部分,如果有多个对数组的引用分散在各处,这可能不是您想要的。
It's not possible to resize an array (or any other object for that matter) once created.
You can use System.Array.Resize(ref T[], int) for a similar effect. However this will actually create a new array with the relevant portions copied across and may not be what you want if there are multiple references to the array scattered around.