Skip to main content
 首页 » 编程设计

c#之如何在其他地方使用范围内的信息

2024年02月05日14mayingbao

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

所以基本上我希望能够在 else if 中使用 item。

请您参考如下方法:

您可以在外部范围内声明变量:

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.