我正在努力学习C#,我在书中遇到了一个问题。 我无法弄清楚为什么它将我的Room objets Exit设置为适当的Loactions,但是我的RoomWithDoor.Exits为null。
public Form1()
{
InitializeComponent();
CreateObjects();
MoveToANewLocation(livingRoom);
}
public void CreateObjects()
{
livingRoom = new RoomWithDoor("living room", "an antique carpet", "an oak door with a brass knob");
livingRoom.Exits = new Locations[] { diningRoom, kitchen };
livingRoom.DoorLocation = frontYard;
diningRoom = new Room("dining room", "crystal chandelier");
diningRoom.Exits = new Locations[] { livingRoom, kitchen };
abstract class Locations
{
public Locations(string name)
{
this.name = name;
}
public Locations[] Exits;
private string name;
public string Name { get { return name; } }
class Room : Locations
{
public Room(string name, string decoration)
: base(name)
{
this.decoration = decoration;
}
class RoomWithDoor : Room, IHasExteriorDoor
{
public RoomWithDoor(string name, string decoration, string doorDescription)
: base(name, decoration)
{
this.doorDescription = doorDescription;
}
所以,这是有效的
private void MoveToANewLocation(Locations newLocation)
{
currentLocation = newLocation;
currentLocationExit = currentLocation.Exits[0];
MessageBox.Show(diningRoom.Name);
但这不是
MessageBox.Show(livingRoom.Exits[0].Name);
答案 0 :(得分:4)
livingRoom = new RoomWithDoor("living room", "an antique carpet", "an oak door with a brass knob");
livingRoom.Exits = new Locations[] { diningRoom, kitchen };
livingRoom.DoorLocation = frontYard;
diningRoom = new Room("dining room", "crystal chandelier");
diningRoom.Exits = new Locations[] { livingRoom, kitchen };
这不能按预期工作。由于您在分配diningRoom
后为livingRoom.Exits
分配了新值,livingRoom.Exits
在分配时仍会保留值diningRoom
,这可能是null
}。
答案 1 :(得分:1)
在餐厅初始化之前,您将餐厅添加到起居室的出口处......
创建餐厅和起居室,然后使用您创建的对象设置出口,否则它们将为null,因为您将出口设置为对空对象的引用,然后将餐厅参考设置为新对象