c# - 如何将多个对象添加到单个数组?

标签 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
}

我会收到一条错误消息,指出数组无法将盔甲对象转换为武器对象(这是数组类型)。然后我想我可能会创建一个 IWeapon 和 IArmour 将从中继承的父类(super class)(准确地说是接口(interface))。但后来我遇到了另一个错误......

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 的属性和方法。因此问题来了,我无法访问位于子类(子接口(interface))IWeapon 中的武器名称。有没有办法以某种方式重定向它以在子接口(interface)(IWeapon 或 IArmour)而不是超接口(interface)(IItem)中查找属性?我走在正确的道路上吗?

最佳答案

因为第一项总是是武器,而第二项总是是盔甲,所以你根本不应该使用数组(或任何数据结构) .只需有两个独立的字段,一个包含武器,另一个包含盔甲实例。

private IWeapon weapon;
private IArmour armor;

public void initialiseInventory(IWeapon weapon, IArmour armour)
{
    this.weapon = weapon;
    this.armor = armor;
}

关于c# - 如何将多个对象添加到单个数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14778355/

相关文章:

java - 数组占用多少空间?

java - 即使在使用全局静态数组之后,我的数组值在 java 中也在发生变化。如何克服呢?

c# - System.Windows.Forms.Trackbar - 如何防止用户拖动 slider ?

c# - DSL:从 DSL 规则到 C# 表达式

java - java中如何对数组进行排序?

JavaScript:对象(变量)是什么?

c# - 数组如何包含不同的对象作为元素?

java - 什么将参数传递给类似 ...(myClass.FINALOBJECT) 的方法?

c# - 通过C#编程用点阵打印机打印

c# - 来自 Azure Application Insights Analytics API 的页面结果