数组不能重新调整大小,你设置它们的时候它们永远是那个大小。
“最佳”选项是使用 aList<int>
而不是int[]
class Check
{
public static void Main()
{
List<int> arr1 = List<int>int[] { 1, 2, 3 };
Console.WriteLine("The Number That Left Us Is");
Random rnd = new Random();
int r = rnd.Next(arr1.Length);
int Left = (arr1[r]);
arr1.RemoveAt(r);
Console.WriteLine(Left);
}
}
要实际创建一个小一号的新数组需要更多的代码。
class Check
{
public static void Main()
{
int[] arr1 = int[] { 1, 2, 3 };
Console.WriteLine("The Number That Left Us Is");
Random rnd = new Random();
int r = rnd.Next(arr1.Length);
int Left = (arr1[r]);
int oldLength = arr1.Length;
arrTmp = arr1;
arr1 = new int[oldLength - 1];
Array.Copy(arrTmp, arr1, r);
Array.Copy(arrTmp, r+1, arr1, r, oldLength - r - 1);
Console.WriteLine(Left);
}
}
您提到“您必须坚持使用数组”,将列表转换为数组非常容易
class Check
{
public static void Main()
{
List<int> arr1 = List<int>int[] { 1, 2, 3 };
Console.WriteLine("The Number That Left Us Is");
Random rnd = new Random();
int r = rnd.Next(arr1.Length);
int Left = (arr1[r]);
arr1.RemoveAt(r);
Console.WriteLine(Left);
SomeFunctionThatTakesAnArrayAsAnArgument(arr1.ToArray());
}
}