开发者

Why must C# extension methods be defined in static classes? [duplicate]

This question already has answers here: Why are extension methods only allowed in non-nested, non-generic static class? (3 answers) Closed 9 years ago.

I und开发者_如何学Cerstand that C# extension methods must be static. What I don't understand is why these extensions can't be defined in non static classes or generic ones?

Update: I am interested in the reason behind this design decision.


This is more of an observation than an answer, but...

When you call an instance method, a reference to the object you are calling is pushed onto the stack as the first argument in your method call. That first argument is "this" and is done implicitly.

When you define an extension method, you explicitly define a "this" as the first argument.

Is it possible that method resolution would be confusing if you could define extension methods and instance methods in the same class i.e. defining methods with the same name and, in effect, the same parameters when the "this" parameter is included.


Take a look to this piece of the .NET C# specification:

When the first parameter of a method includes the this modifier, that method is said to be an extension method. Extension methods can only be declared in non-generic, non-nested static classes. The first parameter of an extension method can have no modifiers other than this, and the parameter type cannot be a pointer type.

And this fragment from Jon Skeet's answer:

It's not clear to me why all of these restrictions are necessary - other than potentially for compiler (and language spec) simplicity. I can see why it makes sense to restrict it to non-generic types, but I can't immediately see why they have to be non-nested and static. I suspect it makes the lookup rules considerably simpler if you don't have to worry about types contained within the current type etc, but I dare say it would be possible.


Because the spec says so... Now there are probably good reasons why they wrote the spec this way.

The reason why they can't be declared in generic classes is quite obvious: given the way extension methods are called, where would you specify the type argument for the class?

The reason why it must be a static class is less obvious, but I think it makes sense. The main use case for static classes is to group helper methods together (e.g. Path, Directory, ProtectedData...), and extension methods are basically helper methods. It wouldn't make sense to be able to create an instance of Enumerable or Queryable, for example.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜