我需要知道如何在 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;
}
你可以使用List<int>
在你的方法逻辑中然后return myIntList.ToArray();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)