首页 > 解决方案 > 从属性调整数组大小

问题描述

private T[] Elements { get; set; }

如果我想调整这个数组的大小,那么我的第一个想法就是这样做:

Array.Resize<T>(ref Elements, Capacity*2)

但它说我不能将属性转换为 out 或 ref

所以我做了这个(编辑):

            T[] tempContainer = new T[Capacity*2];
            Array.Copy(Elements, tempContainer, Capacity);
            Elements = tempContainer

但我不认为这是调整这个数组大小的最有效方法。

感谢您分享您的意见

PS:我的目标是在使用列表的情况下制作动态数组

标签: c#arraysresize

解决方案


您可以尝试像这样处理它:

var tempContainer = Elements;
Array.Resize(ref tempContainer, Capacity*2);
Elements = tempContainer;

此外,您当前的“复制”版本应该会失败,因为两个数组都不够长(对于 tempContainer 总是和对于 Elements in case if Capacity*2> Elements.Length),请参阅docs

另外为什么不声明Elements为字段?


推荐阅读