简体   繁体   English

如何在c#中创建一维动态数组?

[英]how to create a one-dimensional dynamic array in c#?

noob question on c#: how to create a one-dimensional dynamic array? 关于c#的noob问题:如何创建一维动态数组? And how to change it later? 以及如何改变它?

thanks. 谢谢。

Instead of using an array, you can use the List<> object in C#. 您可以在C#中使用List<>对象,而不是使用数组。

List<int> integerList = new List<int>();

To iterate on items contained in the list, use the foreach operator : 要迭代列表中包含的项,请使用foreach运算符:

foreach(int i in integerList)
{
    // do stuff with i
}

You can add items in the list object with Add() and Remove() functions. 您可以使用Add()Remove()函数在列表对象中添加项目。

for(int i = 0; i < 10; i++)
{
    integerList.Add(i);
}

integerList.Remove(6);
integerList.Remove(7);

You can convert a List<T> to an array using the ToArray() function : 您可以使用ToArray()函数将List<T>转换为数组:

int[] integerArray = integerList.ToArray();

Here is the documentation on List<> object. 这是List<>对象的文档

当然听起来你应该查看List<T>

As others have mentioned, a List<T> is likely what you want. 正如其他人所提到的, List<T>可能就是你想要的。 But for completeness, you can resize an array using the Array.Resize static method. 但为了完整性,您可以使用Array.Resize静态方法调整数组大小。 Example: 例:

int[] array = { 1, 2, 3 };
Array.Resize(ref array, 4);

use either: 使用:

ArrayList  //really you should avoid this.
or List<T>

so 所以

var my_list = new List<Your_List_Type_Here>() (Like List<String>);

This way to add you just do: 这样添加你的方法就是:

my_list.Add(Your_Object);

Link to Generic List: http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx 链接到通用列表: http//msdn.microsoft.com/en-us/library/6sh2ey19.aspx

if you want to go back to an array then just call the ToArray() method. 如果你想回到一个数组,那么只需调用ToArray()方法。

Arrays are not dynamic. 数组不是动态的。 If you want something dynamic use a 'List<T>' or some other collection. 如果你想要动态使用'List <T>'或其他一些集合。 You can always call the ToArray() method on it to get an array back. 您始终可以在其上调用ToArray()方法以获取数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM