2

命名的方法MoveToANewRoom(Room newRoom)应该将一个变量设置为一个实例,并且它在方法的过程中这样做,但最后该变量被设置回空,没有明显的原因。

我在调试器中运行了代码,发现在方法执行期间命名的变量currentRoom已按预期设置。但是,当方法完成执行时,变量会再次设置回。room1MoveToANewRoom(Room newRoom)currentRoomnull

我错过了一些非常基本的东西吗?

这是我的代码:

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;
            }
        }
4

1 回答 1

5

currentRoom这是因为您正在定义一个特定于该方法的局部变量。

currentRoom = newRoom;

是完成永久更改的正确语法。

编辑:

为了澄清为什么您的调试器向您显示错误信息:

它向您展示了您选择的上下文值。在这种情况下currentRoom,意味着内部有所不同,MoveToANewRoom因此它“有用地”为您更新了值。至于在这种情况下是否应该进一步澄清,已经引起了很多争论:)。

于 2013-04-11T21:29:04.970 回答