如果一个接口指定了一个属性或方法来返回另一个接口,为什么第一个接口的实现不允许将返回类型“改变”为更具体的类型?
我们举个例子来说明:
interface IFoo
{
IBar GetBar();
}
interface IBar
{ }
class Foo : IFoo
{
// This is illegal, we are not implementing IFoo properly
public Bar GetBar()
{
return new Bar();
}
}
class Bar : IBar
{ }
我知道如何使它工作,那不是我的问题。
我可以:
- 将
GetFoo()
的返回类型更改为IBar
,或者 - 显式实现接口并在
IFoo.GetBar()
方法中调用GetBar
我真正想问的是,为什么不允许上面的代码编译。是否存在任何情况,上述内容未满足由IFoo
指定的契约。