可能的重复:
C# 中未知长度的数组 https://stackoverflow.com/questions/599369/array-of-an-unknown-length-in-c-sharp
我想创建一个程序,用户可以在其中输入项目,这些项目将存储在数组中。当用户对物品数量感到满意时,程序将询问他是否获得了每件物品。
问题是我似乎无法创建一个大小未知的数组。我尝试使用这样的东西: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();
}
Use a List http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx而不是array
.
List<string> myList = new List<string>();
myList.Add("my list item");
收集完所有物品后,您可以使用foreach
循环以迭代集合中的所有项目。
foreach(string listItem in myList)
{
Console.WriteLine(listItem);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)