生成大小未知的数组C#
可能重复:生成大小未知的数组C#,c#,arrays,C#,Arrays,可能重复: 我想创建一个程序,用户可以在其中输入项目,这些项目将存储在一个数组中。当用户对物品的数量满意时,如果他得到了每一件物品,程序将要求它 问题是我似乎无法创建大小未知的数组。我试着使用这样的东西:String[]list=newstring[]{}
我想创建一个程序,用户可以在其中输入项目,这些项目将存储在一个数组中。当用户对物品的数量满意时,如果他得到了每一件物品,程序将要求它 问题是我似乎无法创建大小未知的数组。我试着使用这样的东西:
String[]list=newstring[]{}但是当程序运行到那里时,它会给出一个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();
}
bool groceryListCheck=true;
字符串[]列表=新字符串[]{};
字符串项=null;
字符串yon=null;
int itemsunt=0;
整数计数=0;
while(杂货店检查)
{
Console.WriteLine(“你想买什么商品?”);
item=Console.ReadLine();
列表[计数]=项目;
计数++;
控制台。写入线(“完成?”);
yon=Console.ReadLine();
如果(yon==“y”)
{
groceryListCheck=false;
ItemScont=list.Count();
}
其他的
{
groceryListCheck=true;
}
}
对于(int x=0;x
使用数组而不是数组
List<string> myList = new List<string>();
myList.Add("my list item");
列表
将更容易、更灵活
有很多使用列表的示例,它们向您展示了从列表中提取数据的各种方法。您可以使用列表
,然后,如果您需要数组,您可以调用.ToArray()
方法。为此,我想说您应该使用哈希表。您可以向其中添加任意数量的内容,并且在创建时无需指定大小。有点像一个非常简单的数据库
请参阅:我发现将变量列表变成一个列表是可行的。例如:
bool groceryListCheck = true;
List<string> list = new List<string>();
String item = null;
String yon = null;
int itemscount = 0;
while (groceryListCheck)
{
Console.WriteLine("What item do you wanna go shop for?");
item = Console.ReadLine();
list.Add(item);
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();
}
bool groceryListCheck=true;
列表=新列表();
字符串项=null;
字符串yon=null;
int itemsunt=0;
while(杂货店检查)
{
Console.WriteLine(“你想买什么商品?”);
item=Console.ReadLine();
列表。添加(项目);
控制台。写入线(“完成?”);
yon=Console.ReadLine();
如果(yon==“y”)
{
groceryListCheck=false;
ItemScont=list.Count();
}
其他的
{
groceryListCheck=true;
}
}
对于(int x=0;x
这是完整的代码,对我很有用。初始化时必须知道数组大小。它们不能生长。你想要的是一个列表
关于StackOverflow有很多C#数组问题-你看过了吗?明确地
bool groceryListCheck = true;
List<string> list = new List<string>();
String item = null;
String yon = null;
int itemscount = 0;
while (groceryListCheck)
{
Console.WriteLine("What item do you wanna go shop for?");
item = Console.ReadLine();
list.Add(item);
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();
}