c# - 从属性调整数组大小
问题描述
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:我的目标是在不使用列表的情况下制作动态数组
解决方案
您可以尝试像这样处理它:
var tempContainer = Elements;
Array.Resize(ref tempContainer, Capacity*2);
Elements = tempContainer;
此外,您当前的“复制”版本应该会失败,因为两个数组都不够长(对于 tempContainer 总是和对于 Elements in case if Capacity*2
> Elements.Length
),请参阅docs。
另外为什么不声明Elements
为字段?
推荐阅读
- python-3.x - Django 模型:“ModelFormOptions”对象没有属性“private_fields”
- reactjs - TypeError:无法读取 tsx 文件上未定义的属性“地图”
- selenium-webdriver - Selenium Webdriver + Jmeter + StormRunner 进行性能测试
- angular - 重置表单值后无法设置文本框值
- encryption - 图片,视频在whatsapp中加密了吗?
- python - python datetime到数字var?
- flutter - 如何在颤动中将数组导出到文本文件?
- laravel - 自定义phpword中的文件名
- pyspark - 用 partitionby 写实木复合地板与只是一个循环
- asp.net - 如何在 IIS 中的两个 Web 应用程序 asp.net 和 asp.net 核心之间共享一个简单的字符串值(配置)?