为什么C#实现一个接口时,不允许返回类型的继承 [英] Why C# doesn't allow inheritance of return type when implementing an Interface

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

问题描述

有没有合理的理由,为什么code以下是不合法的,在C#?

 类X:IA,IB
{
    公共X测试()// Compliation错误,说是X不是IB
    {
        回到这一点;
    }
}

接口IA
{
    IB试验(+);
}
接口IB {};
 

解决方案

此功能被称为返回类型的协方差。 C#不支持它的原因如下:

1)CLR不支持它。为了让在C#中,我们不得不只吐了一大堆小帮手的方法做蒙上返回类型正确的事情。没有什么做那自己阻止你。

2)安德斯认为,返回类型的协方差是不是一个很好的语言功能。

3)\我们有很多的语言更高的优先级。我们只有有限的预算,所以我们尽量只做在任何版本的最佳特性,我们可以。当然,这将是很好的,但它是很容易做你自己,如果你想。好,我们花了完善的开发经验或添加更多的重presentational电源的语言。时间增加功能

Is there any rational reason why the code below is not legal in C#?

class X: IA, IB
{
    public X test() // Compliation Error, saying that X is not IB
    {
        return this;
    }
}

interface IA 
{
    IB test();
}
interface IB { };

解决方案

This feature is called "return type covariance". C# does not support it for the following reasons:

1) The CLR doesn't support it. To make it work in C#, we'd have to just spit a whole bunch of little helper methods that do casts on the return type to the right thing. There's nothing stopping you from doing that yourself.

2) Anders believes that return type covariance is not a good language feature.

3) \We have lots of higher priorities for the language. We have only limited budgets and so we try to only do the best features we can in any given release. Sure, this would be nice, but it's easy enough to do on your own if you want to. Better that we spend the time adding features that improve the developer experience or add more representational power to the language.

这篇关于为什么C#实现一个接口时,不允许返回类型的继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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