When do Extension Methods break?

拈花ヽ惹草 提交于 2019-12-05 00:20:34
Marc Gravell

Some curiosities:

  • extension methods might be called on null instances; this might be confusing (but sometimes useful)
  • the "hiding" issue is a biggie if they have different intent
  • equally, you might get a different extension method with the same name from 2 different namespaces; if you only have one of the two namespaces, this could lead to inconsistent behaviour (depending on which)...
  • ...but if somebody adds a similar (same signature) extension method in a second namespace that your code uses, it will break at compile time (ambiguous)

(edit) And of course, there is the "Nullable<T>/new()" bomb (see here)...

I disagree, the whole point of extension methods is to add your members to black boxed classes. Like everything else there are pitfalls, you must be mindful in naming, implementation and understand the pecking order of the methods.

One breakage we've just found in the MoreLINQ project: if you write a generic extension method, it's impossible to make sure it will work with all types. We've got a method with this signature:

public static IEnumerable<T> Concat<T>(this T head, IEnumerable<T> tail)

You can't use that with:

"foo".Concat(new [] { "tail" });

because of the string.Concat method...

I've used Ruby on Rails for almost as long as I've used C#. Ruby allows you to do something similar to the new extension methods. There are, of course, potential problems if someone named the method the same, but the advantages of being able to add methods to a closed class far outweigh the potential dissadvantage (which would probably be caused by bad design or poor planning).

One thing you can do to make sure extension methods don't conflict with other methods (extension or otherwise) is to use FxCop with rules such as Prevent Duplicate Extension Method Signatures.

First of all I believe your wording is a bit misleading. I take it you're talking about "types" and not "objects".

Secondly, the big advantage of extension methods is that you can add features to type you don't control. If you control the type, why not just modify the type instead of relying on extension methods?

We took the attitude in my team that Extension Methods are so useful that you can't realistically ban them, but so dangerous (principally because of the hiding issue) that you have to be a bit cautious. So we decided that all Extension Method names have to be prefixed with X (so we have a bunch of XInit...() methods to initialise controls in useful ways, for instance). That way a) the likelihood of a naming collision is reduced and b) the programmer knows he is using an Extension Method and not a class method.

Joel Coehoorn

What .Net calls extension methods are also a limited form a MonkeyPatching (try to ignore the php rant in there).

That should give you some material for your discussion.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!