如何将多个对象添加到单个阵列?

Fra*_*pie 4 c# arrays object

我正在为游戏设计一个非常简单的库存系统.我遇到了一个障碍,我有一个需要接受多种类型对象的库存(一个特定类型的数组).我的代码:

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
}
Run Code Online (Sandbox Code Playgroud)

我会得到一个错误,指出数组不能将装甲对象转换为武器对象(这是数组类型).然后我想我可以创建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!
}
Run Code Online (Sandbox Code Playgroud)

由于数组类型是IItem,它只包含来自IItem的属性和方法,而不包含来自IWeapon或IArmour的属性和方法.因此问题在于我无法访问位于子类(子接口)IWeapon中的武器的名称.有没有办法我可以以某种方式重定向它以寻找子接口(IWeapon或IArmour)中的属性而不是超级接口(IItem)?我甚至走在正确的道路上吗?

Ser*_*rvy 11

由于第一个项目永远是武器,第二个项目永远是盔甲,因此你根本不应该使用数组(或任何数据结构).只有两个单独的字段,一个持有武器,另一个持有装甲实例.

private IWeapon weapon;
private IArmour armor;

public void initialiseInventory(IWeapon weapon, IArmour armour)
{
    this.weapon = weapon;
    this.armor = armor;
}
Run Code Online (Sandbox Code Playgroud)

  • 如果他真的只有一件武器和一点盔甲,我并不反对你放在这里的东西,但问题的核心似乎是关于物品的多态性...... (4认同)