如何在运行时分配数组值

Aru*_*lam 12 c#

考虑我有一个数组,

int[] i = {1,2,3,4,5};
Run Code Online (Sandbox Code Playgroud)

在这里,我为它分配了值.但在我的问题中,我只在运行时获得这些值.如何将它们分配给数组.

例如:

我从用户获取数组的最大大小,现在我们得到它们的值如何将它们分配给数组int [].

或者我可以使用任何其他数据类型,如ArrayList等,我可以在最后投射到Int []?

Mar*_*ell 19

嗯,最简单的是使用List<T>:

List<int> list = new List<int>();
list.Add(1);
list.Add(2);
list.Add(3);
list.Add(4);
list.Add(5);
int[] arr = list.ToArray();
Run Code Online (Sandbox Code Playgroud)

否则,您需要分配一个合适大小的数组,并通过索引器进行设置.

int[] arr = new int[5];
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
arr[3] = 4;
arr[4] = 5;
Run Code Online (Sandbox Code Playgroud)

如果无法预测数组的大小,则第二种方法无用,因为每次添加项目时重新分配数组的成本都很高; a List<T>使用加倍策略来最小化所需的重新分配.


Seb*_*Seb 12

你的意思是?

int[] array = { 1, 2, 3, 4, 5 };
array = new int[] { 1, 3, 5, 7, 9 };
array = new int[] { 100, 53, 25, 787, 39 };
array = new int[] { 100, 53, 25, 787, 39, 500 };
Run Code Online (Sandbox Code Playgroud)


Jon*_*eet 7

使用List<int>然后ToArray()在最后调用它来创建一个数组.但你真的需要一个阵列吗?使用其他集合类型通常更容易.正如Eric Lippert所写," 阵列被认为有些危害 ".

可以明确地这样做,像这样:

using System;

public class Test
{
    static void Main()
    {
        int size = ReadInt32FromConsole("Please enter array size");

        int[] array = new int[size];
        for (int i=0; i < size; i++)
        {
            array[i] = ReadInt32FromConsole("Please enter element " + i);
        }

        Console.WriteLine("Finished:");
        foreach (int i in array)
        {
            Console.WriteLine(i);
        }
    }

    static int ReadInt32FromConsole(string message)
    {
        Console.Write(message);
        Console.Write(": ");
        string line = Console.ReadLine();
        // Include error checking in real code!
        return int.Parse(line);
    }
}
Run Code Online (Sandbox Code Playgroud)