在这本名为“游戏编程模式”的引人入胜的书中,作者在原型示例中展示了如何使用泛型类在游戏中生成怪物。
免责声明:作者确实指出,代码只是为了给一个概念提供一个示例(而且可能不是完美的)。
这是给定示例中的C++代码:
class Spawner
{
public:
virtual ~Spawner() {}
virtual Monster* spawnMonster() = 0;
};
template <class T>
class SpawnerFor : public Spawner
{
public:
virtual Monster* spawnMonster() { return new T(); }
};调用类将运行:
Spawner* ghostSpawner = new SpawnerFor<Ghost>();我尝试将此示例转换为C#,以便在一个场景中对它进行测试:
public class Spawner<T> {
public virtual Monster SpawnMonster() {
return null;
}
}
class SpawnerTemplate<T> : Spawner {
public override Monster SpawnMonster() {
return new T();
}
}场景中的脚本将运行:
var ghost = new Spawner<Ghost>();Visual不编译,因此我重写如下:
class SpawnerTemplate<T> : Spawner where T : new(){
public override Monster SpawnMonster() {
return new T() as Monster;
}
}调用时仍然存在编译错误:
var ghost = new SpawnerTemplate<Ghost>();必须是具有公共无参数构造函数的非抽象类型,才能将其用作参数。
Ghost代码是这样的:
public class Ghost : Monster
{
public Ghost (int health, int speed) {
this.health = health;
this.speed = speed;
}
public override Monster Clone() {
return new Ghost(health, speed);
}
}我从C++到C#的翻译正确吗?
谢谢
发布于 2020-12-28 18:00:35
不确定这种模式在C#中是否有用,但是:
public class Monster
{
}
public class Ghost : Monster
{
}
public abstract class Spawner
{
public abstract Monster SpawnMonster();
}
public class SpawnerFor<T> : Spawner where T : Monster, new()
{
public override Monster SpawnMonster() { return new T(); }
}然后:
var spawnerForGhost = new SpawnerFor<Ghost>();
var ghost = spawnerForGhost.SpawnMonster();C#的最大限制是可以为无参数构造函数(, new())的存在定义约束,如本例所示,但是如果您希望以参数形式接收new Monster() (new Monster(location)),那么它就会崩溃(参数构造函数不能有约束)。您可以在Monster中明确地定义一个Monster并从SpawnMonster(Location location)调用它)。
https://stackoverflow.com/questions/65480489
复制相似问题