无法访问类公共属性

时间:2016-05-15 05:21:13

标签: c# unity3d

我创建了一个名为Building的类,它有一堆不同类型的房间,但现在我只有一个。我正在尝试访问房间类型类中的属性但由于某种原因它不允许我访问它。

这是我的班级:

public abstract class Building {

    public RoomType roomType { get; private set; }
    public RoomManager roomManager {get; private set;}
    public int x {get; private set;}
    public int y {get; private set;}

    public Building(int x, int y, RoomManager rm, RoomType rT){
        SetPosition(x,y);
        roomManager = rm;
        roomType    = rT;
    }
    void SetPosition(int tx, int ty){
        x = tx;
        y = ty;
    }
}

public class KitchenRoom : Building {
        public Kitchen reference {get; private set;}

        public KitchenRoom(int x, int y, RoomManager rM, Kitchen kitchen) : base(x,y,rM,RoomType.Kitchen){
            reference   = elevator;
        }
}

所以我创建了一个新的KitchenRoom,如下所示:

//Buildings = List<Building>();
//I use type Building because there will be more than just KitchenRoom in this list eventually.

buildings.Add(new KitchenRoom(x,y,go.getComponent<RoomManager>(),go.GetComponent<Kitchen>()));

所以现在我想访问值reference所以我这样做了:

for(int i=0;i<buildings.Count; i++){
    if(buildings[i] is KitchenRoom){
       buildings[i].reference.someMethod(); // access to reference non existant
    }
} 

所以我似乎无法访问reference。但我不知道我在这里遇到了什么问题。

次要小问题:

有人告诉我,使用is KitchenRoom的运行时类型检查不是一个好主意吗?但是我不知道该怎么做,这有什么道理,这是更好的实现吗?

1 个答案:

答案 0 :(得分:4)

问题在于您尝试访问子类中的属性而不先将其强制转换。

属性reference仅存在于您的班级KitchenRoom中,但在Building

中不存在

要访问reference的{​​{1}}属性,您应cast将该元素KitchemRoom

代码示例

KitchenRoom

与问题没有直接关系,但更多的是继续评论中的内容。

is关键字用于检查对象是否属于特定类型。它不执行任何类型的转换,而是用于检查是否可以执行转换而不会抛出错误。

代码示例

for(int i=0;i<buildings.Count; i++){
    if(buildings[i] is KitchenRoom){
       ((KitchenRoom)buildings[i]).reference.someMethod(); // Cast to KitchenRoom first, then access
    }
} 

as关键字是另一种投射方式,如果投射失败,则不会抛出InvalidCastException

代码示例

在上面编写代码的另一种方法

public class Garden : NotBuilding {
    //A class that does not inherit from Building
}


var aBuilding = new Building(); //An object of type building
var aKitchenRoom = new KitchenRoom(); //An object of type KitchenRoom, which inherits from Building in your code


Debug.Log(aBuilding is Building); //true
Debug.Log(aKitchenRoom is Building); //true
Debug.Log(aKitchenRoom is Garden); //false
Debug.Log(aKitchenRoom is NotBuilding); //false