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