如何在c#中创建动态大小的数组或重新调整数组大小?

我需要知道如何在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 ,然后return myIntList.ToArray();

通常,对于此类应用程序,您需要使用List 。 如果你真的需要一个数组,你可以使用ToArray方法但重新考虑一个数组是否真的是你想要的。 通常,List用于动态大小的集合而不是数组。

您可以随时修改代码,如下所示:

 static int[] fillArray() { List list = new List(); do { Console.Write("Please enter a number to add to the array or \"x\" to stop: "); string consoleInput = Console.ReadLine(); if (consoleInput == "x") { return list.ToArray(); } else { list.Add(Convert.ToInt32(consoleInput)); } } while (count < 8); return list.ToArray(); } 

但正如我之前提到的,真的重新考虑更改您的方法以返回List并在您的调用代码中使用List

那么你可以实现自己的方法接受数组和新大小作为参数,这将创建新数组,深层复制元素,然后分配给您的数组。 Array.Resize()也是这样,你可以用反汇编程序来观察它