【发布时间】:2019-10-12 19:48:38
【问题描述】:
我目前正在开发一个基于等距图块的游戏。目前,我有一个带有瓷砖的网格,这些对象包含有关它们的位置、类型和可以放置在它们顶部的各种对象(如树)的数据。
我创建了一个抽象的 TileObject 类,还有一个名为 Tree 的类继承自 TileObject。我的目标是拥有一个静态函数,它负责在不使用构造函数的情况下创建这些 TileObjects。
我也尝试过使用泛型(甚至使用 Activator 类),但似乎没有用。 我的想法是泛型、system.type、typeof,但我无法将这些全部放在一起。
public abstract class TileObject
{
protected TileObject() { }
public Tile Parent { get; set; }
public string ObjectType { get; set; }
public static TileObject CreateObject(string objName, Tile parent)
{
}
}
public class Tree : TileObject
{
}
我认为这个解决方案可以工作,但它似乎很难编码
public static TileObject CreateObject(string objName, Tile parent)
{
TileObject x;
if(objName == "Tree")
x = new Tree();
else if(objName == "Chair")
...
}
【问题讨论】:
-
如何编写单独的方法,如
CreateTree、CreateChair等?