如果方法返回一个接口,它意味着什么?

我看到很多方法将接口指定为返回值。 我的想法是真的,这意味着:我的方法可以返回从该接口inheritance的每个类类型? 如果没有,请给我一个很好的答案。

是的,您的方法可以返回任何实现该接口的类型。

这是一个例子:

using System; class Foo { public IComparable GetComparable() { // Either of these return statements // would be valid since both System.Int32 return 4; // and System.String return "4"; // implement System.IComparable } } 

是的,这意味着您唯一知道的返回对象是它实现了接口。

实际上,调用代码甚至可能无法访问对象的实际类型。 它可以是单独程序集中的私有类型。

实际上,该方法可以从一次调用返回到下一次调用的不同类型(如抽象工厂的情况)。

是的,该方法可能返回实现该接口的任何类型的对象。

但是 ,要使用特定类型的非接口成员,您需要将其强制转换为该类型。

C ++支持一种称为多态的编程技术。 这是一个派生类,对于其他对派生类一无所知的代码,它看起来像一个基类。 看看他的例子:

 class Shape { public: virtual float Area () const = 0; }; class Rectangle: public Shape { public: Rectangle (float width, float height) : m_width(width) , m_height(height) {} virtual float Area () const { return m_width * m_height; } private: float m_width; float m_height; }; class Circle: public Shape { public: Circle (float radius) : m_radius(radius) {} virtual float Area () const { return 3.141592653f*(m_radius*m_radius); } private: float m_radius; }; 

现在你可以从这段代码中看到我们已经创建了一个基类Shape(我们的接口)和两个专门化这个类的派生类,一个是矩形,另一个是圆形。 现在让我们创建一个打印出形状区域的函数:

 void PrintArea (const Shape& shape) { printf("Area of shape = %f",shape.Area()); } 

这个函数不关心它是否是一个矩形圆。 或者它关心的是它通过一个形状,你可以得到它的区域,无论类型。

所以这段代码使用了这个函数:

  Rectangle r (5.0f,4.0f); Circle c (25.0f); PrintArea(r); // Print the area of the rectangle PrintArea(c); // Print the area of the circle 

希望这可以帮助。