首页 > 解决方案 > 初学者制作控制台应用游戏,遇到属性继承问题

问题描述

在我的输入类中,我有一个 switch 语句来过滤所有可能的输入命令。其中之一是“治疗”,我希望它显示玩家拥有的所有治疗项目,并让他们选择使用一个。但是,当我达到玩家按照给定的healItem 可以治愈的量时,healItem 没有“AmountToHeal”的定义。我有一个名为 Item 的类,而 HealItem 是一个派生类。当我输入“playerHealth += healItem.”时,只给出了 Item 的属性。

case "Heal":
                if (player.Inventory.OfType<HealItem>().Any())
                {
                    foreach (var item in player.Inventory)
                    {
                        if (item.GetType() == typeof(HealItem))
                        {
                            Console.WriteLine("You have " + item.Name);
                        }
                    }

                    Console.WriteLine("Which heal item would you like to use? Enter heal item name:");
                    var healItemInput = Console.ReadLine();
                    foreach (var item in player.Inventory)
                    {
                        if (item.GetType() == typeof(HealItem) && healItemInput == item.Name)
                        {

                        }
                    }
                }

在最后的 if() 中,我需要根据healItem 的healAmount 来补充玩家的生命值。

物品类别:

 public class Item
{
    public string Name { get; set; }
    public string Description { get; set; }



}

治疗物品类:

    public class HealItem : Item
{
    public int HealAmount { get; set; }

    public HealItem(string name, string description, int healAmount)
    {
        this.Name = name;
        this.Description = description;
        this.HealAmount = healAmount;
    }
}

标签: c#console-application

解决方案


我不确定我是否完全理解你的问题,但我意识到你说,“当我输入'playerHealth += healItem.'时,只给出了 Item 的属性。”。将问题视为“为什么不显示 HealItem 属性”,您是否尝试过对 HealItem 进行显式强制转换?

代码将如下所示:

playerHealth += ((HealItem)item).HealAmount

为了提高可读性,您可以编写:

HealItem healItem = item
playerHealth += healItem.HealAmount

使用 HealItem 而不是 var 应该将其显式转换为 HealItem 类型。


推荐阅读