扩展方法的优缺点? [英] Disadvantages of extension methods?

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

问题描述

扩展方法是一个非常有用的功能,你可以在任何类添加了很多功能你想要的。但我想知道是否有任何缺点,可能会带来麻烦给我。任何意见或建议?

Extension method is a really helpful feature that you can add a lot of functions you want in any class. But I am wondering if there is any disadvantage that might bring troubles to me. Any comments or suggestions?

推荐答案


  • 的扩展方法是进口的方式(即在整个空间一时间)不是粒状。没有得到所有其他不能导入来自命名空间一个分机。

  • 这是从哪里被定义方法的源代码显而易见。这也是一个的优势的 - 这意味着你可以使你的代码看起来与该类型的方法的其余部分保持一致,即使你不能把它无论出于何种原因在同一个地方。换句话说,将码是简单在较高的水平,以理解,但在<​​青霉>准确的什么正在执行的方面更加复杂。我要说,这是LINQ一般的也是如此。

  • 您只能扩展方法,而不是属性,索引,操作符,构造函数等。

  • 如果您正在扩展第三方类,并在以后的版本,他们引入具有相同签名的新方法,你不会轻易知道你的调用代码的含义发生了变化。如果新的方法是非常的类似的使用你的扩展,但略有不同的边界条件(或其他),那么这可能会导致一些非常棘手的bug。这是比较不太可能发生,虽然

  • The way that extension methods are imported (i.e. a whole namespace at a time) isn't granular. You can't import one extension from a namespace without getting all the rest.
  • It's not immediately obvious from the source code where the method is defined. This is also an advantage - it means you can make your code look consistent with the rest of the methods on the type, even if you can't put it in the same place for whatever reason. In other words, the code is simpler to understand at a high level, but more complicated in terms of exactly what's being executed. I'd argue this is true of LINQ in general, too.
  • You can only have extension methods, not properties, indexers, operators, constructors etc.
  • If you're extending a 3rd party class and in a later version they introduce a new method with the same signature, you won't easily know that the meaning of your calling code has changed. If the new method is very similar to your extension, but with subtly different boundary conditions (or whatever) then this could lead to some very tricky bugs. It's relatively unlikely to happen though.
  • 这篇关于扩展方法的优缺点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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