接口继承.没有实现接口错误

编程入门 行业动态 更新时间:2024-10-28 04:26:19
本文介绍了接口继承.没有实现接口错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在使用继承接口时遇到问题.我将在下面的示例中解释我的问题.假设我有接口 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.

更多推荐

接口继承.没有实现接口错误

本文发布于:2023-11-16 13:33:08,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1604742.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:接口   错误

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!