扩展方法与继承 [英] Extension methods versus inheritance

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

问题描述

有什么经验法则有助于确定在哪种情况下使用?

Are there rules of thumb that help determine which to use in what case? Should I prefer one over the other most times?

谢谢!

推荐答案

p>扩展方法很有用,但是通过IDE比通常的方法更难发现,因为它们没有连接到原始类,并且没有关于它们的代码可能位于何处的线索。有一些最佳做法建议,说明他们在哪里和如何命名他们,但这些只是指导方针,并不能保证有人会跟随他们。

Extension methods are useful, but they are harder to discover through the IDE than regular methods, since they are not attached to the original class and there are no clues as to where the code for them might reside. There are some best practice suggestions as to where to put them and how to name them, but these are only guidelines and there is no guarantee that someone will follow them.

通常你会使用扩展方法,如果你只添加功能到一个众所周知,使用良好的类或接口,如.NET基类,你没有访问的代码。扩展方法也有约束,你不仅必须有原始的程序集,你必须有程序集中的扩展方法,这必须由你的代码的消费者理解。

Usually you would use extension methods if you are only adding functionality to a well known, well used class or interface such as the .Net base classes, that you don't have access to the code for. Extension methods also have the constraint in that you not only have to have the original assembly, you have to have the assembly with the extension methods in it, which must be understood by consumers of your code.

使用继承将允许您添加,删除或覆盖功能,并确保它在构建时始终与类一起出现。

Using inheritance will allow you to add, remove or override functionality, and ensure that it is always present with the class when you build it.

这篇关于扩展方法与继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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