制作一个未知大小的数组C#

Dal*_*lox 7 c# arrays

可能重复:
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();
        }
Run Code Online (Sandbox Code Playgroud)

Dav*_*ych 14

使用List而不是array.

List<string> myList = new List<string>();
myList.Add("my list item");
Run Code Online (Sandbox Code Playgroud)

收集完所有项目后,可以使用foreach循环迭代集合中的所有项目.

foreach(string listItem in myList)
{
    Console.WriteLine(listItem);
}
Run Code Online (Sandbox Code Playgroud)


Bal*_*i C 5

A List<string>会更容易,也更灵活.

有很多使用List 这里的例子,它们向您展示了从中提取数据的各种方法.