如何使用其他地方的信息

时间:2016-09-23 16:47:12

标签: c# scope

我想在另一个代码范围内使用从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

1 个答案:

答案 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.