我需要知道如何動態地重新調整C#中的數組大小。在我下面寫的方法中,我需要能夠返回一個只包含由用戶輸入的最多8個數字的數字的數組。因此,如果用戶決定他們只想輸入3個數字,則該陣列應該只包含3個數字,而不是8個。如何創建一個動態調整大小的數組,或在c#中重新調整數組的大小?
現在我知道數組需要在實例化時包含大小。那麼如何在不使用列表的情況下解決這個問題?循環完成後有沒有辦法重新調整數組大小?
在此先感謝。
static int[] fillArray()
{
int[] myArray;
myArray = new int[8];
int count = 0;
do
{
Console.Write("Please enter a number to add to the array or \"x\" to stop: ");
string consoleInput = Console.ReadLine();
if (consoleInput == "x")
{
Array.Resize(ref myArray, count);
return myArray;
}
else
{
myArray[count] = Convert.ToInt32(consoleInput);
++count;
}
} while (count < 8);
Array.Resize(ref myArray, count);
return myArray;
}
爲什麼不使用像ArrayList或List這樣的可調整大小的集合類型? – 2011-03-01 00:27:01
List <>不過是一個Count和一個Capacity屬性的數組。實現你自己的。 – 2011-03-01 01:01:52