c# - 制作未知大小的数组 C#

标签 c# arrays

<分区>

Possible Duplicate:
Array of an unknown length in C#

我想创建一个程序,用户可以在其中输入项目,这些项目将存储在一个数组中。当用户对元素的数量没有问题时,如果他得到了,程序将询问每件元素。

问题是我似乎无法创建一个大小未知的数组。我尝试使用类似这样的东西:String[] list = new string[]{}; 但是当程序运行到那里时它给出了一个 IndexOutOfRangeException。

我有办法做到这一点吗?

这是完整的代码:

bool groceryListCheck = true;
        String[] list = new string[]{};
        String item = null;
        String yon = null;
        int itemscount = 0;
        int count = 0;

        while (groceryListCheck)
        {
            Console.WriteLine("What item do you wanna go shop for?");
            item = Console.ReadLine();
            list[count] = item;
            count++;
            Console.WriteLine("Done?");
            yon = Console.ReadLine();
            if (yon == "y")
            {
                groceryListCheck = false;
                itemscount = list.Count();
            }
            else
            {
                groceryListCheck = true;
            }
        }

        for (int x = 0; x < itemscount; x++)
        {
            Console.WriteLine("Did you got the " + list[x] + "?");
            Console.ReadKey();
        }

最佳答案

使用 List而不是 array

List<string> myList = new List<string>();
myList.Add("my list item");

收集完所有项目后,您可以使用 foreach 循环遍历集合中的所有项目。

foreach(string listItem in myList)
{
    Console.WriteLine(listItem);
}

关于c# - 制作未知大小的数组 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14608797/

相关文章:

c# - "deep freeze"是如何工作的?

c# - 无法在 Visual Studio 2017 诊断工具中拍摄 native 内存快照

python - 如何在不按元素预先形成的情况下将元组附加到 numpy 数组?

php - 将数组中键的数据类型从数字更改为字符串

php - 如何根据值扩展 implode() 以获取单独的字符串

c# - 根据谓词拆分字符串

c# - 如何下载 Microsoft.TeamFoundation.Framework.Common.dll

c# - 在 C# 中,是否有 "easy"方法来执行 string.Join 复杂类型列表?

javascript - 将对象添加到 javascript 数组,其中列表指定类型

c - 为什么不可能有 void 数组?