2012-03-04 84 views
-3

我正在学习C#,并且我在书中遇到了一个示例问题。 我不知道为什么它将我的房间objets退出到适当的Loactions,但是我的RoomWithDoor.Exits为null。C#继承似乎没有正常工作

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); 
+2

C#继承似乎没有正常工作是的它是越野车:) – 2012-03-04 22:39:57

+1

继承工作很好。然而你的缩进很糟糕。 – 2012-03-04 22:42:44

回答

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

像您期望这是行不通的。由于您在分配livingRoom.Exits之后为diningRoom分配了一个新值,因此livingRoom.Exits在赋值时的值仍然为diningRoom,这可能是null

1

添加餐厅为您的客厅的出口,您已初始化饭厅前...

创建餐厅和客厅,然后使用您创建的对象设置出口,否则设置安永将是空的,因为你将设置出口是一个空对象的引用然后设置餐厅的参考是新的对象