我在使用继承接口时遇到问题.我将在下面的示例中解释我的问题.假设我有接口 IFlyable :
I have a problem with using inherited interface. I will explain my problem on example below. Let's say I have Interface IFlyable:
public interface IFlyable { IVerticalSpeed Speed { get; set; } }它包含 IVerticalSpeed 接口.我创建了另一个名为 ISpeed 的接口,该接口继承自 IVerticalSpeed 接口:
It contains IVerticalSpeed interface. I created another interface called ISpeed which inherits from IVerticalSpeed interface:
public interface ISpeed : IVerticalSpeed { int MaxSpeed { get; set; } }在下一步中,我创建了一个实现 IFlyable 接口的类 Fly :
In next step I created a class Fly which implement IFlyable interface:
public class Fly : IFlyable { public IVerticalSpeed Speed { get; set; } }一切都很好...但是,如果我想将 IVerticalSpeed 接口替换为继承自 IVerticalSpeed 接口的 ISpeed 接口怎么办?
Everything is fine... but what if I wanted to replace IVerticalSpeed interface to ISpeed interface which inherits from IVerticalSpeed interface?
public class Fly : IFlyable { public ISpeed Speed { get; set; } }我认为一切都应该没问题,因为我的 ISpeed 接口是 IVertialSpeed 接口+任何包含 ISpeed 接口的内容.但这是不对的.我收到错误消息:"Fly没有实现接口成员IFlyable.Speed(...).为什么?
I thought that everything should be fine because my ISpeed interface is IVertialSpeed interface + anything that ISpeed interface contatins. But that is not right. I get error which says: "Fly does not implement interface member IFlyable.Speed (...). Why?
推荐答案所有答案都向您显示了可能的解决方案,但实际上没有一个答案可以回答这个重要问题:
All answers show you possible solutions but none actually answer the important question here:
我认为一切都应该没问题,因为我的 ISpeed 接口是 IVertialSpeed 接口+任何包含 ISpeed 接口的内容.但这是不对的.我收到错误消息:"Fly没有实现接口成员 IFlyable.Speed (...).为什么?
I thought that everything should be fine because my ISpeed interface is IVertialSpeed interface + anything that ISpeed interface contatins. But that is not right. I get error which says: "Fly does not implement interface member IFlyable.Speed (...). Why?
您自己说过的. ISpeed 是 IVerticalSpeed ,但并非所有 IVerticalSpeed 都是 ISpeed ,因此您根本不满足合同要求
You've said it yourself. ISpeed is an IVerticalSpeed, but not all IVerticalSpeeds are ISpeeds so you are not satisfying the contract at all.
如果您的代码被允许,而我想执行以下操作,将会发生什么事情:
What would happen if your code was allowed and I wanted to do the following:
public interface IMyOtherSpeed: IVerticalSpeed { ... } IFlyable myFly = new Fly(); IMyOtherSpeed mySpeed = new MyOtherSpeed(); myFly.Speed = mySpeed; //Runtime error, mySpeed is not an ISpeed?!?您现在看到问题了吗?您会违反接口的约定,因为您的类仅在应接受 any IVerticalSpeed 时接受 ISpeed .
You see the issue now? You'd be breaking the interface's contract, becuase your class only accepts ISpeed when it should accept any IVerticalSpeed.
更多推荐
接口继承.没有实现接口错误
发布评论