关于C#的新手问题:如何创建一个一维动态数组?以及如何在之后修改它?
谢谢。
在 C# 中,你可以使用 List<>
对象代替数组。
List<int> integerList = new List<int>();
使用 foreach
运算符来迭代列表中的项目:
foreach(int i in integerList)
{
// do stuff with i
}
您可以使用Add()
和Remove()
函数向列表对象中添加或删除项目。
for(int i = 0; i < 10; i++)
{
integerList.Add(i);
}
integerList.Remove(6);
integerList.Remove(7);
您可以使用ToArray()
函数将List<T>
转换为数组:int[] integerArray = integerList.ToArray();
这里是List<>
对象的文档。
List<T>
。正如其他人所提到的,List<T>
可能是你想要的。但为了完整起见,你可以使用 Array.Resize
静态方法来调整数组大小。例如:
int[] array = { 1, 2, 3 };
Array.Resize(ref array, 4);
请使用以下任一选项:
ArrayList //really you should avoid this.
or List<T>
所以
var my_list = new List<Your_List_Type_Here>() (Like List<String>);
添加的方法如下:
my_list.Add(Your_Object);
通用列表的链接: http://msdn.microsoft.com/zh-cn/library/6sh2ey19.aspx
如果你想返回一个数组,只需调用ToArray()方法。
using System.Linq
以使 Paddy 的想法生效。 - Callum Rogers