【问题标题】:Variable not holding value变量不持有值
【发布时间】:2014-07-03 19:54:36
【问题描述】:

我正在阅读一本可以帮助我学习 C# 的书,其中一个项目类似于在初级 powerpoint 课程中教授的那些旧游戏之一。这个特定的示例使用一个 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;
        }

    }

我有一个与上面完全相同的参考示例,它有效。当按钮“goThroughTheDoor”调用“MoveToANewLocation()”方法时,为什么 currentLocation 失去了它的价值。

抱歉,如果不清楚,我对现代编程还是很陌生

【问题讨论】:

  • 您能解释一下“范围”是什么意思吗?
  • 在哪里声明的?
  • 在您的代码中,看不到 currentLocation 的定义位置。也许它被一遍又一遍地初始化?请显示更多代码。
  • 能否也显示goThroughTheDoorbutton 处理程序的代码?
  • 我假设currentLocation 是一个班级成员。 currentLocation 更改其值的唯一地方是方法的开头,因此问题可能与您的 newLocation 参数有关,而不是与 MoveToANewLocation 方法有关。您应该发布更多代码以使事情更清晰。

标签: c# for-loop null


【解决方案1】:

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

//currentLocation = newLocation;

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

【讨论】:

  • 根据问题,'currentLocation'已经在方法内部丢失了它的值,而不是在方法退出时(参见方法内部的for循环导致错误的描述,因为'currentLocation'没有值)。因此,我认为这并不能回答问题。
猜你喜欢
  • 2011-08-17
  • 2015-08-09
  • 2023-03-17
  • 1970-01-01
  • 2015-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多