简体   繁体   中英

C# OOP - One class can be two different things (Inheritance Issue)

I'm making a console game in C#, and have encountered a problem with the OOP paradigm.

I have an Item class:

class Item
    {
        public int SellPrice;
        public string Name;
    }

And a ShopItem class, which represents Item objects that can be bought in shops:

class ShopItem : Item
    {
        public int Price;
    }

And finally, a weapon class:

class Weapon
    {
        public int Attack, Durability;
    }

Now, every Weapon object is an Item (the inheritance here was purposefully removed), but that creates a major problem.

While you can buy some weapons in shops, you can only get others by completing quests.

So, a Weapon is sometimes a ShopItem (because it could be bought in shops), and sometimes it's just an Item (which cannot be bought in shops).

Items sometimes can be bought in shops if they're ShopItem, though (becuase ShopItem inherits from Item).

So what can I do here? I obviously cannot inherit from both, and if I inherit from the Item class, than I cannot sell the Weapon object in shops (because I wouldn't be able to cast it into a ShopItem).

What do you think is the best solution for such a thing?

You should be thinking in terms of behaviors (methods) instead of properties when designing class hierarchies, ie what can you do with an item?

In your example, I don't think ShopItem should inherit from Item , but rather you should define an interface IBuyable which indicates an Item can be bought.

You could define an interface:

interface IWeapon{}

And change your hierarchy this way:

class ShopWeapon : IWeapon, ShopItem {}
class Weapon : IWeapon, Item {}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM