class bishop:unit {}
class knight:unit {}
class peasant:unit {}
void Battle(unit first, unit second, byte firstAmount, byte secondAmount)
{
System.Array sideA = System.Array.CreateInstance(first.GetType(),firstAmount);
for(int i=0; i< firstAmount; i++)
{
sideA[i] = ???
}
}
在我的最后一个问题中,我在创建动态数组时遇到了问题,这是我的下一步问题! :D
此方法的可传递类型主教,骑士等
其实我现在不明白如何初始化对象。我不能只键入sideA [i] = new first.GetType()(构造函数参数)并理解原因,但是我不知道如何解决此问题
最佳答案
这确实是非常糟糕的设计。
我假设您的方法Battle
可能是您未提供给我们的类Game
的实例方法。
然后,我强烈建议Battle
方法不应创建与其一起使用的对象的实例。它只应该带他们去做战斗动作(计算生命等)。
因此,在其他位置创建这些对象,然后将它们发布到方法中。
class Game
{
List<Bishop> bishops = new List<Bishop>() { new Bishop(..), ... };
List<Knight> knights = new List<Knight>() { new Knight(..), ... };
void Battle(List<Unit> first, List<Unit> second)
{
foreach(var f in first)
{
// get random unit from the second collection and attack him
f.Attack(GetRandomKnight(second));
}
}
public void StartBattle()
{
Battle(bishop, knights);
}
}
另外,请确保使用正确的C#命名。班级名称应以大写字母开头。
class Unit
{
public virtual void Attack(Unit enemy)
{
// default attack
Kick(enemy);
}
protected Kick(Unit enemy) { ... }
}
class Bishop : Unit { }