【问题标题】:Optimal way to represent multiple versions of the same data表示同一数据的多个版本的最佳方式
【发布时间】:2015-12-03 11:39:37
【问题描述】:

我想在我的代码中表示一个房间(房间地图:二维字符串数组、行数、列数)。我需要访问它的四个旋转(90、180、270、0 度)。所有字段:地图、行列在旋转房间时发生变化。 我正在考虑声明四个接口IRoom90IRoom180... 并实现它们,但是我必须编写((IRoom90) myRoom).columns,这似乎并不优雅。

实现此类功能的正确方法是什么?

编辑:我正在考虑一些可以让我获得类似myRoom.rot(90).columns 的访问权限。

【问题讨论】:

    标签: c# data-representation


    【解决方案1】:

    一份数据副本和一个公共方法来执行轮换。冗余数据将是一个坏主意。您只需要一组基于旋转量进行的计算。您可以为您描述的 4 个旋转编写 4 个公共方法,或者只编写一个带参数的公共方法。

    您还可以为 4 次旋转创建枚举数据类型,并要求将其实例传递给旋转方法。这将消除方法中的参数验证。

    【讨论】:

    • 请参阅编辑操作。无论如何,我不明白你的第二段。你能改写一下吗?
    【解决方案2】:

    好的。所以我想出了这个:

    public class Room
        {
            public class OrientedRoom{
                Direction dir;
                Room disoriented;
                OrientedRoom(Direction dir, Room disoriented){
                    this.dir = dir;
                    this.disoriented = disoriented;
                }
                public int Cols{
                    get{
                        if(dir==Direction.North || dir == Direction.South)
                            return disoriented.cols;
                        else
                            return disoriented.rows;
                    }
                }
                public int Rows{
                    get{
                        if(dir==Direction.North || dir == Direction.South)
                            return disoriented.rows;
                        else
                            return disoriented.rows;
                    }
                }
                public string this[int i, int j]{
                    get{
                        switch(dir){
                        case Direction.West: return disoriented.map[Cols-j-1, i];break;
                        case Direction.South:return disoriented.map[Rows-i-1, Cols-j-1];break;
                        case Direction.East: return disoriented.map[j,Rows-i-1]; break;
                        case Direction.North:return disoriented.map[i, j];break;
                        }
                    }
                }
            }
            public readonly int cols;
            public readonly int rows;
            private string[,] map;
            public int score;
            public string name;
    
            public enum Direction{North, South, East, West};
            public OrientedRoom rot(Direction dir){
                return new OrientedRoom (dir, this);
            }
    

    我很乐意听到任何改进它的建议。

    【讨论】:

      猜你喜欢
      • 2016-11-28
      • 2021-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多