【发布时间】: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方法有关。您应该发布更多代码以使事情更清晰。