如何处理不同类型的物品

问题描述 投票:1回答:1

我正在与基于网格的库存系统进行统一游戏,但我遇到了问题。我不知道如何处理清单中的不同类型的项目。

e.g

我有一个类Item

class Item
{
    public int ID;
    public string name;
}

然后我有继承Item类的武器类

class Weapon: Item
{
    public int damage;
}

和材料类

class Material : Item
{
    public int hardness;
}

我的问题是如何将它们放在像List<Item> inventory这样的列表中,并且仍然可以访问它们的所有属性。这是解决这个问题的好方法还是我需要一个完全不同的系统?

c# unity3d
1个回答
2
投票

您可以使用isas C#运算符来查找并将对象转换为其派生类型。请参阅以下示例:

class Item
{
    public int ID;
    public string name;
}

class Weapon : Item
{
    public int damage;
}

class Material : Item
{
    public int hardness;
}


void Main()
{
    List<Item> inventory = new List<Item>();
    inventory.Add(new Weapon
    {
        name = "weapon",
        ID = 1,
        damage = 10,
    });


    inventory.Add(new Material
    {
        name = "material",
        ID = 1,
        hardness = 100,
    });

    foreach (var item in inventory)
    {
        if (item is Weapon)
        {
            var weapon = item as Weapon;
            weapon.Dump();
        }
        if (item is Material)
        {
            var material = item as Material;
            material.Dump();
        }
    }

}

你可以看到更多的例子here

© www.soinside.com 2019 - 2024. All rights reserved.