簡體   English   中英

如何在c#中創建一維動態數組?

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

關於c#的noob問題:如何創建一維動態數組? 以及如何改變它?

謝謝。

您可以在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/en-us/library/6sh2ey19.aspx

如果你想回到一個數組,那么只需調用ToArray()方法。

數組不是動態的。 如果你想要動態使用'List <T>'或其他一些集合。 您始終可以在其上調用ToArray()方法以獲取數組。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM