我正在写一个库,我想要一个接口(interface)
public interface ISkeleton
{
IEnumerable<IBone> Bones { get; }
void Attach(IBone bone);
void Detach(IBone bone);
}
Attach() 和 Detach() 实现对于每个 ISkeleton 实际上应该是相同的。因此,它基本上可以是:
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 类吗?或者有什么技巧和方法吗?
最佳答案
如果您需要在接口(interface)中公开Attach
和Detach
方法,总有一种方法可以绕过您的预期实现,因为实现该接口(interface)的所有对象都可以实现他们以自己的风格。
您可以让抽象类 Skeleton
实现 ISkeleton
并且所有属于 Skeleton 的类都继承自 Skeleton
,因此它们实现了 ISkeleton
也是。
public interface ISkeleton { ... }
public abstract class Skeleton : ISkeleton { ... } // implement attach and detach
public class SampleSkeleton : Skeleton { ... }
这样你就可以把你的SampleSkeleton
当作ISkeleton
来使用,只要继承自Skeleton
就不必实现这些功能并将方法标记为 sealed
不允许覆盖它们(只要它们是实例方法)。
在侧节点上:请在末尾使用 Base
命名您的抽象类,或者以其他方式标记基类(但这肯定取决于您)。
关于c# - 没有抽象类的实现接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10210027/