0

好的,所以我有一本 int 和 Tile 类型的字典。我有一个名为 TileManager 的类,我正在设计它以返回某个图块的新实例。现在这就是我所拥有的。

public class TileManager
{
    private Dictionary<int, Tile> _registeredTiles = new Dictionary<int, Tile>();

    public Tile GetNewTile(int id)
    {
        // Here, I need to return a new instance of the tile at the given key. I want
        // something like this: return new _registeredTiles[id].GetType();
    }
    . . .
}

问题是,我不能只创建一个新的 Tile 类,因为它将包含除 Tile 之外的不同类(它将包含 Tile 的子级)。

4

1 回答 1

1

最简单的解决方案是使用Activator.CreateInstance();

如果需要,您可以将类型和构造函数参数数组传递给它:

return (Tile)Activator.CreateInstance(_registeredTiles[i].GetType());
于 2013-09-22T23:19:21.630 回答