【问题标题】:Different objects from one interface with different methods and properties来自具有不同方法和属性的一个接口的不同对象
【发布时间】:2019-06-14 05:39:00
【问题描述】:

这是我的界面

interface IEnemy
    {
        int Health { get; set; }
    }

以及少数派生自它的类

public class Goblin : IEnemy
    {
        public int Health { get; set; }
        public Goblin()
        {
            Health = 50;
            Console.WriteLine("You encounter an Enemy Goblin!");
        }
    }
public class Undead : IEnemy
    {
        public int Health { get; set; }
        public Undead()
        {
            Health = 100;
            Console.WriteLine("You encounter an Enemy Undead!");
        }
    }
public class Orc : IEnemy
    {
        public int Health { get; set; }
        public Orc()
        {
            Health = 150;
            Console.WriteLine("You encounter an Enemy Orc!");
        }
    }

假设我想制作一个随机发生器来选择要生成的敌人---我制作了这样的东西

IEnemy enemy = new Goblin() or Undead() or Orc()...

一切都按预期工作,但例如,当一个对象,比如 Goblin,有一个接口没有的方法时,如果敌人是 IEnemy 类型,我该如何调用该方法?

【问题讨论】:

  • 问题是:“为什么我需要在接口上调用特定于类的函数?”

标签: c# methods interface


【解决方案1】:

你可以写

if (enemy is Goblin goblin) {
    goblin.CallGoblinMethod();
}

但问题是这是否是一个好的设计。最好有具有普遍“品味”的方法,在不同的对象中以不同的方式实现。它们甚至可能在某些对象中为空。

或者你可以通过另一个接口概括一个行为

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

【讨论】:

  • 是的,我想知道,我只是想知道是否有更好的方法,无论如何,谢谢。
猜你喜欢
  • 1970-01-01
  • 2013-08-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多