C# 如何在运行时分配数组值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/724501/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 22:35:55  来源:igfitidea点击:

How to assign array values at run time

c#

提问by Arunachalam

Consider I have an Array,

考虑我有一个数组,

int[] i = {1,2,3,4,5};

Here I have assigned values for it. But in my problem I get these values only at runtime. How can I assign them to an array.

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

For example:

例如:

I get the max size of array from user and the values to them now how do I assign them to the array int [].

我从用户那里获得了数组的最大大小以及给他们的值,现在如何将它们分配给数组 int []。

Or can I use anyother data types like ArrayList etc which I can cast to Int[] at the end?

或者我可以使用任何其他数据类型,如 ArrayList 等,我可以在最后将其转换为 Int[] 吗?

采纳答案by Marc Gravell

Well, the easiest is to use List<T>:

好吧,最简单的是使用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();

Otherwise, you need to allocate an array of suitable size, and set via the indexer.

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

int[] arr = new int[5];
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
arr[3] = 4;
arr[4] = 5;

This second approach is not useful if you can't predict the size of the array, as it is expensive to reallocate the array every time you add an item; a List<T>uses a doubling strategy to minimize the reallocations required.

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

回答by Jon Skeet

Use List<int>and then call ToArray()on it at the end to create an array. But do you reallyneed an array? It's generally easier to work with the other collection types. As Eric Lippert wrote, "arrays considered somewhat harmful".

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

You cando it explicitly though, like this:

可以明确地做到这一点,就像这样:

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);
    }
}

回答by Slavo

If you want an array, whose size varies during the execution, then you should use another data structure. A generic List will do. Then, you can dynamically add elements to it.

如果您想要一个在执行过程中大小会发生变化的数组,那么您应该使用另一种数据结构。一个通用的 List 就可以了。然后,您可以向其动态添加元素。

Edit:Marc posted his answer while I was writing mine. This was exactly what I meant.

编辑:马克在我写我的时候发布了他的答案。这正是我的意思。

回答by Seb

You mean?

你的意思是?

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 };

回答by Druthi

You could just use the below line instead of calling a separate function:

您可以只使用以下行而不是调用单独的函数:

using System;

public class Test
{
    static void Main()
    {
        Console.WriteLine("Please enter array size");
        int size = Convert.ToInt32(Console.ReadLine());

        int[] array = new int[size];
        for (int i=0; i < size; i++)
        {
            Console.WriteLine("Please enter element " + i);
            array[i] = Convert.ToInt32(Console.ReadLine());
        }

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