【问题标题】:How to handle different types of items如何处理不同类型的物品
【发布时间】:2017-12-23 06:04:02
【问题描述】:

我正在使用基于网格的库存系统制作一个统一的游戏,但我遇到了一个问题。我不知道如何处理库存中不同类型的物品。

例如

我有一堂课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】:

您可以使用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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-01
    相关资源
    最近更新 更多