【发布时间】:2013-09-16 19:50:32
【问题描述】:
这是一款基于 OOP 的角色扮演游戏。我在将对象作为接口处理时遇到了麻烦。
abstract class Items
{
public string name { get; set; }
}
所有项目都有名称,这是我想要获得的属性。
interface Ieatable
{
int amountHealed { get; set; }
}
会治疗一个玩家。
class Healers : Items, Ieatable
{
private int heal;
public int amountHealed
{
get { return heal; }
set { heal = value; }
}
public Healers(int amount, string name)
{
heal = amount;
base.name = name;
}
}
这里是我处理可食用物品的地方。我浏览了玩家背包中的每件物品。然后我检查该项目是否可食用。然后是我正在努力的部分,检查玩家背包中的物品之一是否与作为参数传入的可食用物品相同。
public void eatSomethingt(Ieatable eatable)
{
foreach (Items i in items ) //Go through every item(list) in the players backpack
{
if (i is Ieatable && i.name == eatable.name) //ERROR does not contain definition for name
{
Ieatable k = i as Ieatable;
Console.WriteLine(Name + " ate " + eatable.name); //Same ERROR here.
life = life + k.amountHealed;
items.Remove(i);
break;
}
}
}
【问题讨论】:
-
在接口中定义
Name属性 -
该错误告诉您确切的问题是什么。
Ieatable没有name的定义。你对什么感到困惑? -
尽量避免使用复数形式。所有项目的类别应为
Item。 -
我想你是想说
as Items,而不是as Ieatable。 -
@EricLippert 不,
i已经属于Items类型,不是吗?
标签: c# oop interface abstract-class