接口+分机(混入)与基类 [英] Interface + Extension (mixin) vs Base Class

查看:128
本文介绍了接口+分机(混入)与基类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是一个接口+扩展方法(混入)preferable到一个抽象类?

如果你的答案是看情况,这是什么取决于?

If your answer is "it depends", what does it depend upon?

我看到两种可能的优势,以接口+推广方法。

I see two possible advantages to the interface + extension approach.

  • 在接口是多重继承和类都没有。
  • 您可以使用扩展方法来扩展接口,在不换的方式。 (实现你的接口的客户端将获得新的基实现,但仍然可以覆盖它。)

我还没有想到一个缺点这种做法。有可能是一个离谱原因很简单,接口+推广方法会失败。

I have not yet thought of a downside to this approach. There may be a glaringly simple reason that the interface + extension approach will fail.

有关此主题的两个有用的文章是

Two helpful articles on this topic are

  • Create Mixins with Interfaces and Extension Methods
  • Abstract Base Classes Have Versioning Problems Too

推荐答案

的扩展方法不足:客户preC#3 / VB9将不能够简单地使用它

Downside of extension methods: clients pre-C#3/VB9 won't be able to use it as easily.

这就是它,据我而言 - 我认为,基于接口的方法是显著更好。然后,您可以模拟出你的依赖关系很好,一切基本上是不太紧密耦合。我不是类继承一个巨大的风扇,除非它的的确确是专业化:)

That's about it as far as I'm concerned - I think the interface-based approach is significantly nicer. You can then mock out your dependencies nicely, and everything is basically less tightly coupled. I'm not a huge fan of class inheritance unless it's really about specialization :)

编辑:我只是想的其中之一的其他利益可能的是相关的。这有可能是一些具体的实现中的可提供的一些的一般方法更加优化的版本。

I've just thought of one other benefit which might be relevant. It's possible that some of the concrete implementations could provide more optimized versions of some of the general methods.

Enumerable.Count 就是一个很好的例子 - 它明确地检查是否序列实现的IList 与否,因为如果这样做,可以调用计数列表,而不是通过整个序列迭代上。如果的IEnumerable< T> 曾是一个抽象类,虚拟计数()的方法,它可能已经在覆盖名单,其中,T> ,而不是那里是一个单一的实现,它明确地知道 IList中。我不是说这始终是相关的,也不是说的IEnumerable< T> 应该是一个抽象类 - 只是指出它作为一个小的可能的缺点(绝对不是!) 。这就是多态性真的是合适的,通过专业现有行为(不可否认的方式,它只影响结果的表现,而不是)。

Enumerable.Count is a good example of this - it explicitly checks whether the sequence implements IList or not, because if it does it can call Count on the list instead of iterating through the whole sequence. If IEnumerable<T> had been an abstract class with a virtual Count() method, it could have been overridden in List<T> rather than there being a single implementation which knows about IList explicitly. I'm not saying this is always relevant, nor that IEnumerable<T> should have been an abstract class (definitely not!) - just pointing it out as a small possible disadvantage. That's where polymorphism really would be appropriate, by specializing existing behaviour (admittedly in a way which only affects performance instead of the result).

这篇关于接口+分机(混入)与基类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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