c# - 如何从已声明为接口(interface)的基类中获取值?

标签 c# oop interface abstract-class

这是一款基于 OOP 的角色扮演游戏。我在将对象作为接口(interface)处理时遇到问题。

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

        }

    }

最佳答案

否则我会定义它。

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


}

关于c# - 如何从已声明为接口(interface)的基类中获取值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18836141/

相关文章:

c# - 如何使用 XPATH 解析以下具有命名空间的内容?

c# - 实现缺少新约束的通用接口(interface)

c# - 为什么这个字段被声明为私有(private)的并且也是只读的?

c# - 未在接口(interface)中定义的属性的 setter

C# 对象、接口(interface)和数据库

c# - PayPal API 混淆 - ExpressCheckout 使用哪一个

c# - 流畅的验证仍然显示来自 [Required] 数据注释的错误

引用、对象和指针之间的 C++ 区别

java - 是否可以在另一个类中重写一个类的方法?

php - 在 PHP 中,你如何创建可重用对象?对此有最佳实践吗?你喜欢哪个?