接口 + 扩展(mixin)与基类 [英] Interface + Extension (mixin) vs Base Class

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

问题描述

接口+扩展方法(mixin)是否比抽象类更可取?

如果您的答案是取决于",那取决于什么?

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

推荐答案

扩展方法的缺点:C#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,因为如果实现了,它可以调用 Count 在列表中,而不是遍历整个序列.如果 IEnumerable 是一个带有虚 Count() 方法的抽象类,它可以在 List 中被覆盖,而不是而不是有一个明确知道 IList 的实现.我并不是说这总是相关的,也不是 IEnumerable 应该是一个抽象类(绝对不是!) - 只是指出它是一个可能的小缺点.这就是多态真正适合的地方,通过专门化现有行为(无可否认,这种方式只会影响性能而不是结果).

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).

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

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