如何创建一个动态大小的数组,或重新大小在C#中的数组? [英] How do I create a dynamically sized array, or re-size an array in c#?

查看:972
本文介绍了如何创建一个动态大小的数组,或重新大小在C#中的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要知道如何动态调整大小在C#中的数组。在我已下面所写的方法,我需要能够以返回仅包含由用户最多8个数字是输入的数字数组。因此,如果用户决定他们只需要输入3个数字,数组应该只包含3个数字,而不是8。

现在我知道,数组需要实例化时,包括大小。那么,如何解决这个问题,而无需使用列表?有没有办法循环完成后,重新大小的数组?

先谢谢了。

 静态INT [] fillArray()
    {
        INT [] myArray的;
        myArray的=新INT [8];
        诠释计数= 0;
        做
        {
            Console.Write(请输入一个数字添加到阵列中或\\X \\停止);
            字符串consoleInput =到Console.ReadLine();
            如果(consoleInput ==×)
            {
                Array.Resize(REF myarray的,算);
                返回myArray的;
            }
            其他
            {
                myArray的[计] = Convert.ToInt32(consoleInput);
                ++计数;
            }        }而(COUNT< 8);        Array.Resize(REF myarray的,算);
        返回myArray的;    }


解决方案

您可以使用列表< INT> 你的方法逻辑,然后在返回myIntList.ToArray();

I need to know how to dynamically re-size an array in C#. In the method that I have written below, I need to be able to return an array that only contains the numbers that were input by the user up to 8 numbers. So if the user decides they only want to enter 3 numbers, the array should only contain 3 numbers, not 8.

Now I know that an array needs to include a size when instantiated. So how do I get around this without using a list? Is there a way to re-size the array after the loop is done?

Thanks in advance.

        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;

    }

解决方案

You could use a List<int> during your method logic and then return myIntList.ToArray();

这篇关于如何创建一个动态大小的数组,或重新大小在C#中的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆