可以说我有这样的界面:
public interface MyInterface { int Property1 { get; } void Method1(); void Method2(); }
有没有办法强制接口的实现者明确地实现它的一部分?就像是:
public interface MyInterface { int Property1 { get; } explicit void Method1(); explicit void Method2(); }
编辑:至于为什么我关心界面是否明确实现;就功能而言,它并不重要,但是使用代码隐藏一些不必要的细节可能会有所帮助.
我正试图在我的系统中模仿多重继承,使用这种模式:
public interface IMovable { MovableComponent MovableComponent { get; } } public struct MovableComponent { private Vector2 position; private Vector2 velocity; private Vector2 acceleration; public int Method1() { // Implementation } public int Method2() { // Implementation } } public static IMovableExtensions { public static void Method1(this IMovable movableObject) { movableObject.MovableComponent.Method1(); } public static void Method2(this IMovable movableObject) { movableObject.MovableComponent.Method2(); } } public class MovableObject : IMovable { private readonly MovableComponent movableComponent = new MovableComponent(); public MovableComponent MovableComponent { get { return movableComponent; } // Preferably hiddem,all it's methods are available through extension methods. } } class Program { static void Main(string[] args) { MovableObject movableObject = new MovableObject(); movableObject.Method1(); // Extension method movableObject.Method2(); // Extension method movableObject.MovableComponent // Should preferably be hidden. } }
如果MovableComponent属性是显式实现的,那么在大多数情况下,它将对使用该类的任何人隐藏.希望解释不是太可怕.
解决方法
不,不可能强制实施者选择接口的显式或隐式实现.