繁体   English   中英

如何仅部分实现具有抽象类的接口时满足编译器?

[英]How to satisfy the compiler when only partially implementing an interface with an abstract class?

我这里有一个名为IFish的界面。 我想用抽象类( WalkingFishCommon )派生它,它提供了一个不完整的实现,因此从WalkingFishCommon派生的类不必实现CanWalk属性:

interface IFish
{
    bool Swim();
    bool CanWalk { get; }
}

abstract class WalkingFishCommon : IFish
{
    bool IFish.CanWalk { get { return true; } }

    // (1) Error: must declare a body, because it is not marked
    // abstract, extern, or partial
    // bool IFish.Swim();

    // (2) Error: the modifier 'abstract' is not valid for this item
    // abstract bool IFish.Swim();

    // (3): If no declaration is provided, compiler says 
    // "WalkingFishCommon does not implement member IFish.Swim()"
    // {no declaration}

    // (4) Error: the modifier 'virtual' is not valid for this item
    // virtual bool IFish.Swim();

    // (5) Compiles, but fails to force derived class to implement Swim()
    bool IFish.Swim() { return true; }
}

我还没有发现如何使编译器满意,同时仍然实现了强制从WalkingFishCommon派生的类来实现Swim()方法的目标。 特别令人困惑的是(1)和(2)之间的差异,其中编译器在抱怨Swim()没有标记为抽象之间交替,并且在下一次呼吸中抱怨它不能被标记为抽象。 有趣的错误!

有帮助吗?

只需将Swim声明为abstract ,不要尝试使用显式接口声明(即删除IFish )。

abstract class WalkingFishCommon : IFish
{
    public bool CanWalk { get { return true; } }
    public abstract bool Swim();
}

通常,通过在接口的每个成员的类中定义公共成员来隐式实现接口:

class MyFish : IFish
{
    public bool CanWalk { get { return ...; } }

    public bool Swim() { return ...; }
}

如果您不想为其中一个成员提供实现,您可以简单地将其设为抽象:

abstract class FishBase : IFish
{
    public virtual bool CanWalk { get { return true; } }

    public abstract bool Swim();
}

如果确实需要显式实现接口,则可以创建两个成员:一个必须由派生类覆盖的抽象成员,以及一个实现接口并将调用转发给第一个成员的成员:

abstract class FishBase : IFish
{
    public virtual bool CanWalk { get { return true; } }

    protected abstract bool Swim();

    bool IFish.Swim() { return Swim(); }
}

如果您不需要显式实现接口,则可以执行以下操作:

abstract class WalkingFishCommon : IFish {
    public abstract bool CanWalk { get; }
    public abstract bool Swim();

}

如果显式实现很重要,您可以通过引入受保护的抽象方法来解决问题:

abstract class WalkingFishCommon : IFish {
    bool IFish.CanWalk { get { return CanWalkCore; } }
    bool IFish.Swim() { return SwimCore(); }

    protected abstract bool CanWalkCore { get; }
    protected abstract bool SwimCore();

}

不完全是一个解决方案,但也许你可以做类似的事情

interface IWalkingFish
{
    bool CanWalk { get; }
}

interface ISwimmingFish
{
    bool Swim();
}

interface IFish : ISwimmingFish, IWalkingFish
{ }

abstract class WalkingFishCommon : IWalkingFish
{
    bool IWalkingFish.CanWalk { get { return true; } }
}

然后,您可以使用抽象和具体类的不同接口。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM