为什么不继承工作,我认为它应该工作的方式吗? [英] Why doesn't inheritance work the way I think it should work?

查看:167
本文介绍了为什么不继承工作,我认为它应该工作的方式吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有,因为我已经有了一组需要全部重写,共同创造一个客户端实现相互关联的抽象类的一些继承的问题。我非常希望做类似如下:

I'm having some inheritance issues as I've got a group of inter-related abstract classes that need to all be overridden together to create a client implementation. Ideally I would like to do something like the following:

abstract class Animal
{
  public Leg GetLeg() {...}
}

abstract class Leg { }

class Dog : Animal
{
  public override DogLeg Leg() {...}
}

class DogLeg : Leg { }

这将使用人的狗类来自动获取狗腿和使用动物类人获得腿允许。问题是,重写的函数必须具有相同类型的基类,所以这不会编译。我不明白为什么它不应该虽然,因为狗腿隐式浇注料腿部。我知道有很多办法解决这个,但我更好奇,为什么这是不可能的/在C#中实现的。

This would allow anyone using the Dog class to automatically get DogLegs and anyone using the Animal class to get Legs. The problem is that the overridden function has to have the same type as the base class so this will not compile. I don't see why it shouldn't though, since DogLeg is implicitly castable to Leg. I know there are plenty of ways around this, but I'm more curious why this isn't possible/implemented in C#.

修改 :我修改这个有点,因为我实际使用在我的代码属性,而不是功能。

EDIT: I modified this somewhat, since I'm actually using properties instead of functions in my code.

修改:我改回功能,因为答案只适用于这种情况(方差属性上的集函数参数的值不该的工作)。很抱歉的波动!我知道这让很多的答案似乎无关紧要。

EDIT: I changed it back to functions, because the answer only applies to that situation (covariance on the value parameter of a property's set function shouldn't work). Sorry for the fluctuations! I realize it makes a lot of the answers seem irrelevant.

推荐答案

简短的回答是,GetLeg在其返回类型不变。长的答案可以在这里找到:的协方差和逆变

The short answer is that GetLeg is invariant in its return type. The long answer can be found here: Covariance and contravariance

我想补充一点,虽然继承通常是第一个抽象的工具,大部分开发商拔出他们的工具箱,它几乎总是可以使用组合物来代替。组成的API开发人员略多的工作,但使得它的消费者的API更加有用。

I'd like to add that while inheritance is usually the first abstraction tool that most developers pull out of their toolbox, it is almost always possible to use composition instead. Composition is slightly more work for the API developer, but makes the API more useful for its consumers.

这篇关于为什么不继承工作,我认为它应该工作的方式吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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