1

这是一款基于 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;
            }

        }

    }
4

3 回答 3

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);


}
于 2013-09-16T19:58:48.360 回答
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);
}
于 2013-09-16T20:21:52.093 回答
0

在 Items 上创建接口

interface IITems
{
    string name { get; set; }
}

abstract class Items : IItems
{ ....

然后在 IEatable 中使用它

public interface IEatable : IItems
{ ....

然后治疗师类:

public class Healers : IEatable
{ ...

然后你应该能够访问 IEatable 类型的 name 属性

于 2013-09-16T20:01:25.107 回答