在我的输入类中,我有一个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; }
}
HealItem类:
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;
}
}
我不确定我是否完全理解您的问题,但我意识到您说过,“当我输入'playerHealth + = healItem时,仅提供Item的属性。”。以“为什么不显示HealItem属性”为问题,您是否尝试过对HealItem进行显式转换?
代码看起来像这样:
playerHealth += ((HealItem)item).HealAmount
为了提高可读性,您可以编写:
HealItem healItem = item
playerHealth += healItem.HealAmount
使用HealItem而不是var应该将其显式转换为HealItem类型。
找到了解决方案!我制作了一个HealItem类型的临时列表,并遍历了该列表以选择治疗项目。完美地工作。