没有抽象类的实现接口?

Jak*_*ake 4 .net c# abstract-class interface-implementation

我正在写一个库,我想要一个界面

public interface ISkeleton
{
    IEnumerable<IBone> Bones { get; }
    void Attach(IBone bone);
    void Detach(IBone bone);
}
Run Code Online (Sandbox Code Playgroud)

对于每个ISkeleton,Attach()和Detach()实现实际上应该是相同的.因此,它基本上可以是:

public abstract class Skeleton
{
    public IEnumerable<IBone> Bones { get { return _mBones; } }

    public List<IBone> _mBones = new List<IBone>();

    public void Attach(IBone bone)
    {
         bone.Transformation.ToLocal(this);
         _mBones.add();
    }

    public void Detach(IBone bone)
    {
        bone.Transformation.ToWorld(this);
         _mBones.Remove(bone);
    }
}
Run Code Online (Sandbox Code Playgroud)

但是C#不允许多重继承.因此,在各种问题中,用户每次想要实现Skeleton时都必须记住从Skeleton继承.

我可以使用扩展方法

public static class Skeleton
{   
    public static void Attach(this ISkeleton skeleton, IBone bone)
    {
         bone.Transformation.ToLocal(skeleton);
         skeleton.Bones.add(bone);
    }

    public static void Detach(this ISkeleton skeleton, IBone bone)
    {
        bone.Transformation.ToWorld(this);
         skeleton.Bones.Remove(bone);
    }
}
Run Code Online (Sandbox Code Playgroud)

但后来我需要

public interface ISkeleton
{   
    ICollection<IBone> Bones { get; }
}
Run Code Online (Sandbox Code Playgroud)

这是我不想要的,因为它不是协变的,用户可以绕过Attach()和Detach()方法.

问题:我必须真正使用抽象的Skeleton类,还是有任何或技巧和方法?

Mat*_*ten 5

如果需要在接口中公开AttachDetach方法,总会有一种方法绕过预期的实现,因为实现接口的所有对象都可以按照自己的样式实现它们.

您可以让抽象类Skeleton实现,ISkeleton并且所有Skeletons类都继承Skeleton,因此它们也可以实现ISkeleton.

public interface ISkeleton { ... }

public abstract class Skeleton : ISkeleton { ... } // implement attach and detach

public class SampleSkeleton : Skeleton { ... }
Run Code Online (Sandbox Code Playgroud)

这样你就可以使用你的SampleSkeletonas ISkeleton,你不必实现这些函数,只要你继承Skeleton并标记方法,就像sealed不允许覆盖它们一样(只要它们是实例方法).

在一个侧节点上:用Base最后的名称命名你的抽象类,或者以其他方式标记基类(但这肯定取决于你).