假设我有一个这样的界面:
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 属性是显式实现的,那么在大多数情况下,它会对使用该类的任何人隐藏。希望这个解释不要太可怕。