为什么接口实现不能返回更具体的类型? [英] Why can't an interface implementation return a more specific type?

查看:211
本文介绍了为什么接口实现不能返回更具体的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果接口指定了返回另一个接口的属性或方法,为什么第一个接口的实现不允许将返回类型更改为更具体的类型?

If an interface specifies a property or method to return another interface, why is it not allowed for implementations of the first interface to "change" the return type into a more specific type?

让我们举一个例子来说明:

Let's take an example to illustrate:

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
{ }

我知道如何让它发挥作用,我的担忧。

I know how to make it work, that's not my concern.

I可以只是:


  • GetFoo()的返回类型更改为 IBar ,或

  • 明确地实现接口,只需从<$ c调用 GetBar $ c> IFoo.GetBar()方法

  • Change return type of GetFoo() to IBar, or
  • Explicitly implement the interface and just call GetBar from the IFoo.GetBar() method

我真正在问的是不仅仅是因为推理允许上面的代码编译。是否有任何上述情况不符合 IFoo 指定的合同。

What I am really asking is the reasoning for not just allowing the code above to compile. Is there any case where the above doesn't fulfill the contract specified by IFoo.

推荐答案

通常,我会说这是一个平衡利益与支持这种功能的额外复杂性的案例。 (所有功能都需要设计,记录,实现,测试,然后开发人员也需要了解它们。)请注意,如果您想支持返回实现接口的值类型,可能会有一些重大的复杂性,例如(因为它以不同的表示形式结束,而不仅仅是参考)。

Usually, I'd say that it would be a case of balancing the benefit against the added complexity of supporting such a feature. (All features take effort to design, document, implement, test, and then developers need to be educated about them too.) Note that there could be some significant complexities if you wanted to support returning a value type which implemented an interface, for example (as that ends up in a different representation, rather than just a reference).

在这种情况下,我不相信 CLR甚至支持这样一个功能,这将使C#很难干净利落。

In this case, I don't believe the CLR even supports such a feature, which would make it very hard for C# to do so cleanly.

我同意这是一个有用的功能,但我怀疑它没有被认为足以保证所需的额外工作。

I agree it would be a useful feature, but I suspect it hasn't been deemed useful enough to warrant the extra work required.

这篇关于为什么接口实现不能返回更具体的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆