我需要知道如何在C#中动态调整数组大小.在下面我写的方法中,我需要能够返回一个只包含用户输入的数字的数组,最多包含8个数字.因此,如果用户决定他们只想输入3个数字,则该数组应该只包含3个数字,而不是8个.
现在我知道数组在实例化时需要包含一个大小.那么如何在不使用列表的情况下解决这个问题呢?循环完成后有没有办法重新调整数组的大小?
提前致谢.
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;
}
Run Code Online (Sandbox Code Playgroud)