c# - 初学者制作控制台应用游戏,遇到属性继承问题
问题描述
在我的输入类中,我有一个 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;
}
}
解决方案
我不确定我是否完全理解你的问题,但我意识到你说,“当我输入'playerHealth += healItem.'时,只给出了 Item 的属性。”。将问题视为“为什么不显示 HealItem 属性”,您是否尝试过对 HealItem 进行显式强制转换?
代码将如下所示:
playerHealth += ((HealItem)item).HealAmount
为了提高可读性,您可以编写:
HealItem healItem = item
playerHealth += healItem.HealAmount
使用 HealItem 而不是 var 应该将其显式转换为 HealItem 类型。
推荐阅读
- python-2.7 - 在 Python 中计算系列中项目类型的数量
- mysql - 如何创建聚合函数?
- c++ - int64_t 在传递给函数时更改值
- c++ - std::greater 在双精度和类的 std::pair 上
- parameters - 收到错误“request.all 不是函数”,并且 request.param 和 request.params 不再是 AdonisJS 中的函数
- ubuntu - 在 ubuntu 上将请求定向到不同端口上的 localhost 的最简单方法是什么?
- python - 如何使用 OneHotEncoder 和 Pipeline 进行新的预测?
- amazon-web-services - AWS CloudFormation 创建 RDS 集群并将其 ARN 添加到同一模板中的策略
- google-drive-api - 无法更新或删除共享云端硬盘项目的继承权限
- flutter - 如何应用 BackdropFilter 模糊除中心以外的整个背景?