我正在为一款游戏设计一个非常简单的库存系统。但是遇到了障碍,因为我的库存(特定类型的数组)需要接受多种类型的物品。以下是我的代码:
IWeapon[] inventory = new IWeapon[5];
public void initialiseInventory(IWeapon weapon, IArmour armour)
{
inventory[0] = weapon; // Index 0 always contains the equipped weapon
inventory[1] = armour; // Index 1 always contains the equipped armour
}
我会得到一个错误,指出数组无法将防具对象转换为武器对象(这是数组类型)。然后我想我可以制作一个超类(确切地说是接口),让IWeapon和IArmour从中继承。但是我又遇到了另一个错误...
IItem[] inventory = new IItem[5];
public void initialiseInventory(IWeapon weapon, IArmour armour)
{
inventory[0] = weapon; // Index 0 always contains the equipped weapon
inventory[1] = armour; // Index 1 always contains the equipped armour
Console.WriteLine("The weapon name is: " + inventory[0].Name) // Problem!
}
由于数组类型是IItem,它只包含来自IItem的属性和方法,而不是来自IWeapon或IArmour的。因此问题出现了,我无法访问位于子类(子接口)IWeapon中的武器名称。有没有办法将其重定向以查找子接口(IWeapon或IArmour)而不是超级接口(IItem)中的属性?我是否在正确的道路上?