在 C# 中动态创建数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/881133/
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-05 05:13:09  来源:igfitidea点击:

Dynamically Create an Array in C#

c#

提问by saurabh

How can I dynamically create an array in C#?

如何在 C# 中动态创建数组?

采纳答案by Bojan Resnik

You can also use the newoperator just like with other object types:

您还可以new像使用其他对象类型一样使用运算符:

int[] array = new int[5];

or, with a variable:

或者,使用变量:

int[] array = new int[someLength];

回答by Natrium

First make an arraylist. Add/remove items. And then ArrayList.ToArray()

首先制作一个数组列表。添加/删除项目。进而ArrayList.ToArray()

And there is your array!

还有你的阵列!

回答by Matthew Flaschen

object foo = Array.CreateInstance(typeof(byte), length);

回答by Gerrie Schenck

I'd like to add to Natrium's answer that generic collections also support this .ToArray() method.

我想在 Natrium 的回答中补充一点,泛型集合也支持这个 .ToArray() 方法。

List<string> stringList = new List<string>();
stringList.Add("1");
stringList.Add("2");
stringList.Add("3");
string[] stringArray = stringList.ToArray();

回答by blitzkriegz

Use generic List or ArrayList.

使用通用列表或 ArrayList。

回答by Michael Dausmann

Ok so array initialisation gets me every single time. so I took 10 minutes to do this right.

好吧,数组初始化每次都让我得到。所以我花了 10 分钟才把这件事做好。

    static void Main(string[] args)
    {
        String[] as1 = new String[] { "Static", "with", "initializer" };
        ShowArray("as1", as1);

        String[] as2 = new String[5];
        as2[0] = "Static";
        as2[2] = "with";
        as2[3] = "initial";
        as2[4] = "size";
        ShowArray("as2", as2);

        ArrayList al3 = new ArrayList();
        al3.Add("Dynamic");
        al3.Add("using");
        al3.Add("ArrayList");
        //wow! this is harder than it should be
        String[] as3 = (String[])al3.ToArray(typeof(string));
        ShowArray("as3", as3);

        List<string> gl4 = new List<string>();
        gl4.Add("Dynamic");
        gl4.Add("using");
        gl4.Add("generic");
        gl4.Add("list");
        //ahhhhhh generic lubberlyness :)
        String[] as4 = gl4.ToArray();   
        ShowArray("as4", as4);
    }

    private static void ShowArray(string msg, string[] x)
    {
        Console.WriteLine(msg);
        for(int i=0;i<x.Length;i++)
        {
            Console.WriteLine("item({0})={1}",i,x[i]);
        }
    }

回答by sina rezaei

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

for (int i=0;i<=array.Length-1 ;i++ ) {
  Console.WriteLine(array[i]);
}