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

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

问题描述

是一个接口+扩展方法(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

推荐答案

下拉方法:客户端pre-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< T> 已经是一个具有虚拟 Count()方法的抽象类,它可能已被覆盖列表< 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).

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

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