如果一个方法返回一个接口,那意味着什么?
我看到许多方法都指定接口作为返回值。我的想法是否正确,这意味着:我的方法可以返回从该接口继承的每个类类型?如果没有请给我一个好的答案。
I see many methods that specify an interface as return value. Is my thought true that it means: my method can return every class type that inherits from that interface? if not please give me a good answer.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
是的,您的方法可以返回实现该接口的任何类型。
这是一个例子:
Yes, your method could return any type that implements that interface.
Here is an example:
是的,这意味着您对返回的对象唯一了解的是它实现了接口。
事实上,调用代码甚至可能无法访问对象的实际类型。它可以是单独程序集中的私有类型。
事实上,该方法可能会从一次调用到下一次调用返回不同的类型(就像抽象工厂的情况一样)。
Yes, it means that the only thing you know about the object that is returned is that it implements the interface.
In fact, the actual type of the object may not even be accessible to the calling code. It could be a private type in a separate assembly.
And in fact, the method may return a different type from one invocation to the next (as in the case of an abstract factory).
是的,该方法可能会返回实现该接口的任何类型的对象。
但是,要使用特定类型的非接口成员,您需要将其强制转换为该类型。
Yes, that method might return an object of any type that implements that interface.
But, to use the non-interface members of a particular type, you'll need to cast it to that type.
C++ 支持一种称为多态性的编程技术。也就是说,对于其他对派生类一无所知的代码来说,派生类看起来就像基类。看一下他的示例:
现在您可以从这段代码中看到,我们创建了一个基类 Shape(我们的接口)和两个专用于此类的派生类,一个是矩形,另一个是圆形。现在让我们创建一个打印形状面积的函数:
该函数不关心它是否是矩形的圆。或者它关心的是它传递了一个形状,并且无论类型如何,您都可以获得它的面积。
所以这段代码使用了这个函数:
希望这有帮助。
C++ supports a programming technique called polymorphism. That is a derived class can look like a base class to other code that knows nothing about the derived classes. Take a look at his example:
Now you can see from this code we've created a base class Shape (our interface) and two derived classes that specialise this class, one a rectangle, another a circle. Now let's create a function that prints out the area of a shape:
This function doesn't care if its a circle of rectangle. Or it cares about is that it's passed a shape and that you can get the area of it, regardless of type.
So this code uses this function:
Hope this helps.