变量不持有价值

5 c# null for-loop

我正在编写一本帮助我学习C#的书,其中一个项目就像是在小学电脑课程中教授的旧游戏之一.此特定示例使用for循环定义房间或区域有多少出口(外门).

这是通过外门移动的一个例子.当我回到门口时,使用"MoveToANewLocation()"方法,"currentLocation"失去了它的价值.for循环随后将值设置为负值,从而导致错误.

private void MoveToANewLocation(Location newLocation)
    {
        currentLocation = newLocation;

        exits.Items.Clear();
        for (int i = 0; i < currentLocation.Exits.Length; i++)
        {
            exits.Items.Add(currentLocation.Exits[i].Name);
        }

        exits.SelectedIndex = 0;

        description.Text = currentLocation.Description;

        if (currentLocation is IHasExteriorDoor)
        {
            goThroughTheDoor.Visible = true;
        }
        else
        {
            goThroughTheDoor.Visible = false;
        }

    }
Run Code Online (Sandbox Code Playgroud)

我有一个与上面完全相同的参考示例,它有效.当按钮"goThroughTheDoor"调用"MoveToANewLocation()"方法时,我很难理解为什么currentLocation会丢失它的值.

抱歉,如果不清楚,我仍然是现代编程的新手

小智 0

当该MoveToANewLocation方法开始时,它设置currentLocation为参数的副本newLocation

//currentLocation = newLocation;
Run Code Online (Sandbox Code Playgroud)

当方法退出时,就会currentLocation超出范围,并且垃圾收集器可以清理该内存以将内存用于范围内的对象。这解释了退出该方法后其值如何丢失。