我想在另一个代码范围内使用从ReadLine()
收集的信息。
我创建了一个菜单,我正在使用if语句。
如果我想使用菜单中选项1中收集的信息,并将其写入选项2,我该如何去做?
if (selectMenu == 1)
{
Console.WriteLine("What item will you put in the backpack?");
//Console.ReadLine();
string item = Console.ReadLine();
}
else if (selectMenu == 2)
{
}
所以基本上我希望能够在item
中使用else if
。
答案 0 :(得分:4)
您可以在外部范围内声明变量:
string item = null;
if (selectMenu == 1)
{
Console.WriteLine("What item will you put in the backpack?");
item = Console.ReadLine();
}
else if (selectMenu == 2)
{
}
... you could use the item variable here but it will have its default value of null
if selectMenu was different than 1 because in this example we assign it
only inside the first if.