操作数组属性的索引值get / set

时间:2015-12-09 19:27:14

标签: c# arrays properties game-engine

在我正在构建的游戏引擎中(为了好玩),开发人员可以创建地下城,其中包含一维地牢阵列,其中包含一个二维的房间阵列。

每个楼层可以偏离其他楼层(例如,允许楼层居中),我想修改get()阵列的rooms,使楼层垂直对齐将具有无论两个楼层的大小和偏移,都是相同的(每层)坐标。

例如,想象一个5 * 5大小的地牢。它上面的楼层是3 * 3.二楼偏移(1,1),这意味着我应该拨打dungeon.floors[0].rooms[2, 2]dungeon.floors[1].rooms[2,2],我应该找回两个直接位于上方/下方的房间彼此。

floor 1  floor 0  floor 1 with offset
 ■ ■ ■  ■ ■ ■ ■ ■  X X X X
 ■ O ■  ■ ■ ■ ■ ■  X ■ ■ ■
 ■ ■ ■  ■ ■ O ■ ■  X ■ O ■
        ■ ■ ■ ■ ■  X ■ ■ ■
        ■ ■ ■ ■ ■
Drawn diagram of the above example, the circle represents the room that should be selected.
The Xs in the last plan show how the offset should be 'visualised'.
Note the selected rooms overlap should floor 0 and floor 1 with offset be overlaid.

以下是工作代码,省略了方法和不相关的细节。 我是否可以通过描述的属性访问器来完成它,或者我是否必须使用类索引器?

struct Offset
{
    int x, y;
}

class Dungeon
{
    public DungeonFloor[] floors { get; private set; }
    public int Height { get; private set; }
}

class DungeonFloor
{
    public int Width { get; private set; }
    public int Height { get; private set; }
    public Offset offset {get; private set;}
    public Room[,] rooms {
        get
        {
            //What do I put here??
            //Is it even possible to access the index values in this context?
        }
        private set; 
    }
}

class Room { }

(我知道我可能会通过调用数组的实际尺寸大小来替换Width / Height)

1 个答案:

答案 0 :(得分:2)

我不确定我是否完全理解这个问题,但我认为你想要的是一个索引器,请参阅此处的文档:https://msdn.microsoft.com/en-us/library/6x16t2tx.aspx

一个简单的例子:

class DongeonFloor
{
    private room[,] room=new room[rows,columns];
    public Room this[int i,int j] {
    get
    {
        return room[i+1,j+1]; //modify for whatever the offset is 
    }
    private set{
        room[i-1,j-1]=value;
    }


}