这是一款基于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;
}
}
}
答案 0 :(得分:3)
我会另外定义。
// The base interface for all items.
public interface INamedItem
{
string Name { get; set; }
}
// all classes are derived from INamedItem, so you can always have the Name property.
public interface IEatable : INamedItem
{
int AmountHealed { get; set; }
}
public class Healers : Ieatable
{
public string Name { get; set; }
public int AmountHealed { get; set; }
public Healers(int amountHealed, string name)
{
AmountHealed = amountHealed;
Name = name;
}
}
示例:
public void eatSomethingt(IEatable eatable)
{
var eatItem = items.OfType<IEatable>.Where( item => item.Name == eatable.Name).FirstOrDefault();
if (eatItem == null)
return;
life = life + eatItem.amountHealed;
Console.WriteLine(Name + " ate " + eatable.name); //Same ERROR here.
items.Remove(i);
}
答案 1 :(得分:2)
您无需更改设计,因为其他答案表明您的EatSomething
方法有效。只需更改传递的内容类型:
public void eatSomethingt(Healer healer)
{
foreach (Items i in items)
{
if (i is Ieatable && i.name == healer.name)
{
Ieatable k = i as Ieatable;
Console.WriteLine(Name + " ate " + healer.name);
life = life + k.amountHealed;
items.Remove(i);
break;
}
}
}
对此答案的警告是,您可能需要IEatable
,而不是Item
(或Healer
)。但是,在这种情况下,您可能没有要比较的名称,因此需要单独的方法。
您传递给方法的IEatable
来自哪里?我认为它源于鼠标点击库存项目,因此,您可以这样做:
public void eatSomethingt(Healer item)
{
Console.WriteLine(Name + " ate " + item.name);
life = life + item.amountHealed;
items.Remove(item);
}
答案 2 :(得分:0)
在Items
上创建一个接口interface IITems
{
string name { get; set; }
}
abstract class Items : IItems
{ ....
然后在IEatable中使用它
public interface IEatable : IItems
{ ....
然后是治疗师班:
public class Healers : IEatable
{ ...
然后您应该能够访问IEatable类型的名称属性