我正在写一个库,我想要一个界面
public interface ISkeleton
{
IEnumerable<IBone> Bones { get; }
void Attach(IBone bone);
void Detach(IBone bone);
}
对于每个 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);
}
}
但是 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);
}
}
但我需要有
public interface ISkeleton
{
ICollection<IBone> Bones { get; }
}
我不想要,因为它不是协变的,用户可以绕过 Attach() 和 Detach() 方法。
问题:我必须真的使用抽象 Skeleton 类还是有任何技巧和方法?