【问题标题】:How to use a method from another class if both classes implement the same interface如果两个类都实现相同的接口,如何使用另一个类的方法
【发布时间】:2021-12-29 00:11:26
【问题描述】:

所以这是我正在尝试做的一个例子:

 public interface IFlyable
    {
        void Fly();
    }
    internal abstract class Insect { }
    internal class Bee : Insect, IFlyable
    {
        public void Fly()
        {
            //some implementation
        }
    }
    internal class Hornet : Insect, IFlyable
    {
        public void Fly()
        {
            //here I want the same implementation as in Bee.Fly()
        }
    }

作为一个不希望只是复制粘贴实现的完整新手,我能想到的唯一有意义的方法是为飞行昆虫创建另一个抽象类并从那里继承所需的一切:

internal abstract class Insect { }
internal abstract class FlyingInsect : Insect, IFlyable
{
 public void Fly()
 {
    //implementation
 }
}
internal class Bee : FlyingInsect
{

}
internal class Hornet : FlyingInsect
{

}

即使这解决了我的问题,我仍然想知道有什么更好的替代方法,特别是如果有一种方法允许不创建另一个“统一”类,而是调用/接受这个已经从另一个使用相同接口的类实现的方法。 提前致谢。

【问题讨论】:

    标签: c# oop interface polymorphism


    【解决方案1】:

    这取决于您想要什么耦合,但是如果 所有 飞虫都将使用该实现(或者只有少数不使用该实现,您可以将其覆盖为必要的)。以下是一些其他选项:

    • Insect 添加一个内部方法,BeeHornet 都调用(不过,如果它只适用于飞虫,这似乎有点奇怪)
    • Hornet 调用的Bee 添加一个静态方法(Bee.Fly 也必须调用它)
    • 在两个都调用的其他位置添加静态方法(“实用程序”或“帮助”方法?)。

    请注意,没有一种“聪明”的方法可以仅仅因为它们实现相同的接口就自动调用其他类的实现。从表面上看,实现共享行为的中间类型似乎是最佳选择。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-03
      • 1970-01-01
      • 2014-08-15
      • 1970-01-01
      • 2014-10-25
      相关资源
      最近更新 更多