1

我有这样的事情:

public class Map
{
    class DataHandler
    {
        private int posX, posY;
        // Other attributes

        public int GetX() { return posX; }
        public int GetY() { return posY; }
        // Other functions for handling data (get/set)
    }

    class FileHandler
    {
        // Functions for reading/writing setting files
    }

    DataHandler Data;
    FileHandler Files;

    public Map()
    {
        Data = new DataHandler();
        Files = new FileHandler();
    }
}

现在,当我编写设置文件时,我需要读取类的一些变量(非静态)DataHandler。例如,假设我想使用and方法获取posXand的值,以便将它们写入文件中。如何从“文件”实例访问地图中的“数据”实例?我知道我可以将 DataHandler 类的实例作为参数传递给写入文件的函数,但这并不像我想的那样。在我的想法中,它应该自己读取数据(在这种情况下),因为它在同一个类中。有没有一种干净的方法可以做到这一点?posYGetXGetYposXposYMap

编辑:

我可以将类的实例传递MapFileHandler构造函数,因此它可以访问其父类和数据,但我知道这不是解决问题的好方法。所以,改变我的结构是没有问题的,我明白它有问题,否则我不会有这个问题,但我不知道如何改变它。如果您有任何建议,请随时写下来。

只是为了更好地解释上下文。我有一张地图,它由各种数据(x、y、高度、宽度、名称……)和一些描述它的图像组成(例如,地形高度的 RGB 图像,我已经计划好了类来处理图像)和一些设置文件。在其中一个文件中必须写入一些地图数据。所以,我的想法是有一个父 Map 类,里面有处理数据、图像和文件的三个类,但是出现了这个问题,所以我认为这不是一个好的结构。

4

2 回答 2

2

在我的想法中,它应该自己读取数据(在这种情况下是 posX 和 posY),因为它在同一个 Map 类中。有没有一种干净的方法可以做到这一点?

不可以。你必须在你的班级DataHandler和班级之间来回传递数据,他们不会自动获知彼此的存在。FileHandlerMap

如果你能解释一下一切应该做什么,那真的很有帮助,因为你的类名似乎有点太笼统了。

于 2013-05-22T14:33:02.953 回答
0

If you strongly against changing structure (but it is recommended way) I suggest you refactor DataHandler and FileHandler - implement it as Singleton, so in any line of your code you can access it as via DataHandler.Instance.GetX() and FileHandler.Instance.SomeMethod().

Basic implementation of singleton is:

class DataHandler
{
    private DataHandler() {}
    public GetX() { ... }

    private static DataHandler instance = null;

    public static Instance
    {
        get
        {
            if (instance == null)
            {
                return (instance = new DataHandler());
            }
        }
    }
}

UPD: My sample is not thread-safe.

于 2013-05-22T14:35:19.333 回答