命名的方法MoveToANewRoom(Room newRoom)
应该将一个变量设置为一个实例,并且它在方法的过程中这样做,但最后该变量被设置回空,没有明显的原因。
我在调试器中运行了代码,发现在方法执行期间命名的变量currentRoom
已按预期设置。但是,当方法完成执行时,变量会再次设置回。room1
MoveToANewRoom(Room newRoom)
currentRoom
null
我错过了一些非常基本的东西吗?
这是我的代码:
public partial class Form1 : Form
{
Room currentRoom;
public Form1()
{
InitializeComponent();
Room room1 = new Room("Living Room");
Room room2 = new Room("Dining Room");
Room room3 = new Room("Kitchen");
Room room4 = new Room("Front Yard");
Room room5 = new Room("Back Yard");
Room room6 = new Room("Garden");
room1.Exits = new Room[] { room2, room3 };
room2.Exits = new Room[] { room1, room4 };
room3.Exits = new Room[] { room1, room4 };
room4.Exits = new Room[] { room2, room3, room5, room6 };
room5.Exits = new Room[] { room4 };
room6.Exits = new Room[] { room4 };
MoveToANewRoom(room1);
}
public class Room
{
public string Name;
public Room[] Exits;
public Room(string name)
{
this.Name = name;
}
}
public void MoveToANewRoom(Room newRoom)
{
Room currentRoom = newRoom;
exits.Items.Clear();
for (int i = 0; i < currentRoom.Exits.Length; i++)
{
exits.Items.Add(currentRoom.Exits[i].Name);
exits.SelectedIndex = 0;
}
}