Why can't static method in non-static class be an extension method? [duplicate]

。_饼干妹妹 提交于 2019-11-29 06:03:36

问题


Possible Duplicate:
extension method requires class to be static

In .NET:

Why can't static method in non-static class be an extension method?


回答1:


Eric Lippert will probably weigh in with a really good answer on this one, but the gist of it will probably be:

We decided it would be easier on both programmers and the compiler if we limit the number of places that you have to look for extension methods.

This policy tends to force users to put all of their extension methods into a few specific classes that are designated for this purpose.




回答2:


It makes sense that a static class is required to have extension methods. The number one reason is that the static class is stateless ...i.e. you don't have to instance the class. ...but this is just my gut feeling. It wouldn't make sense to me otherwise.

I think, too, that forcing extension methods to reside in public/internal static classes reduces the cost of using them.




回答3:


Because, well, that's the way it is.

My guess would be that allowing static extension methods would complicate the language (every feature adds complexity of one type or another) while adding almost zero benefit. If you are defining a static method on String for example, what's the benefit in doing so when you can simply define your own class with the same static method?

Instance level extension methods are useful because they work on the current state of a type instance. The static method has no context, so it would not provide any utility over a static method defined elsewhere aside from logical grouping (i.e., defining a String.IsNullOrFullOfSomeChar(char c) would logically make sense to belong to the String class, but aside from that there is no advantage. And yes, that would be a horrible method, just an example).

Extension methods came about as a result of LINQ. They were implemented to get LINQ working the way that the designers wanted. Static extensions were not required and, as such, they were not implemented.




回答4:


At compile time whenever you use the instance syntax sugar for extension methods, this is converted into a call to the static method (which defines the extension), and passes through your instance.

Apart from the nice syntax it's no different to implementing a static method and passing your instance through as an argument. This is exactly what happens. You can't do this with static classes, as you can't pass a static class as a parameter to a method.



来源:https://stackoverflow.com/questions/7405751/why-cant-static-method-in-non-static-class-be-an-extension-method

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