C# 一个接口中的不同对象具有不同的方法和属性
这是我的界面C# 一个接口中的不同对象具有不同的方法和属性,c#,methods,interface,C#,Methods,Interface,这是我的界面 interface IEnemy { int Health { get; set; } } interface IThief { void Steal(); } public class Goblin : IEnemy, IThief { public int Health { get; set; } public Goblin() { Health = 50; Console.Wr
interface IEnemy
{
int Health { get; set; }
}
interface IThief
{
void Steal();
}
public class Goblin : IEnemy, IThief
{
public int Health { get; set; }
public Goblin()
{
Health = 50;
Console.WriteLine("You encounter an Enemy Goblin!");
}
public void Steal()
{
//TODO: steal
}
}
从中派生的类也很少
public class Goblin : IEnemy
{
public int Health { get; set; }
public Goblin()
{
Health = 50;
Console.WriteLine("You encounter an Enemy Goblin!");
}
}
比如说,我想做一个随机发生器,它选择要繁殖的敌人——我做了类似这样的东西
IEnemy enemy = new Goblin() or Undead() or Orc()...
一切都按预期运行,但例如,当一个对象(比如Goblin)有一个接口没有的方法时,如果敌人是IEnemy类型,我怎么能调用该方法 你可以写
if (enemy is Goblin goblin) {
goblin.CallGoblinMethod();
}
但问题是这是否是一个好的设计。最好有一个通用的“味道”方法,在不同的对象中实现不同的方法。在某些对象中,它们甚至可能是空的
或者,您可以通过另一个接口概括行为
interface IEnemy
{
int Health { get; set; }
}
interface IThief
{
void Steal();
}
public class Goblin : IEnemy, IThief
{
public int Health { get; set; }
public Goblin()
{
Health = 50;
Console.WriteLine("You encounter an Enemy Goblin!");
}
public void Steal()
{
//TODO: steal
}
}
像这样,你甚至不需要知道敌人是地精。在游戏的进化过程中,可能会出现其他具有相同能力的生物
if (enemy is IThief thief) {
thief.Steal();
}
是的,我在想,我只是想知道是否有更好的方法来实现这一点,谢谢。问题是:“为什么我需要在接口上调用特定于类的函数?”