接口如何替代类?
我创建了一个名为 GetStudentMarks()
的方法。此方法的返回类型是通用 List
。即使我用通用 IList
。当接口只包含声明时,接口如何替换类?List
,该代码也能正常工作。
I created a Method called GetStudentMarks()
. The return-type of this method is generic List<StudentMark>
.The code works well even when i replaced the List<StudentMark>
with generic IList<StudentMark>
. How can an interface replace a class while interface contain only the declarations?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
接口不能代替类。它只是一个类的蓝图,该类具有一些与接口设置的准则相对应的实现。因此,您通常会拥有一个接口和 1 个或多个具有该接口的某种实现的类,如下所示:
An interface cannot replace a class. It's just a blueprint for a class that has some implementation that corresponds by the guidelines that are set by the interface. So, you mostly will have one interface and than 1 or multiple classes that have some implementation for that interface like so:
返回类型是接口还是实体类并不重要。由于在方法内部您要返回完整类型,因此在返回实际数据之前,该类型会被转换为声明的返回类型,因此一切都会按预期工作。
稍后,如果需要,可以将返回类型 (IList) 强制转换回实体类 (List) 并以这种方式使用它。
It doesn't matter if the return type is interface or a solid class. Since inside the method you're returning the full type, the type is casted to the declared return type before returning the actual data so everything works as expected.
Later if you require, you can cast the return type (IList) back to the solid class (List) and use it that way.
Interface
不能替代Class
。接口
可以创建一个抽象层,隐藏接口之外的实际对象实现(这就是它被称为接口的原因)。请参阅多态性获取解释。
Interface
can not replace theClass
.Interface
can create an abstraction layer that hides actual object implementation beyound interface (that's why it's called interface).Look on Polymorphism for explanation.