【发布时间】: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