Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
464 views
in Technique[技术] by (71.8m points)

c# - Extension methods require declaring class to be static

Why do extension methods require the declaring class to be static? Is it a compiler requirement?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It's dictated in the language specification, section 10.6.9 of the C# 4 spec:

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.

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.

I suspect that the extra complexity of not having these restrictions was deemed less than the benefit gained.

EDIT: Just to be clear, I'm not suggesting that it would make sense to have instance methods as extension methods - I'm suggesting that it would make sense to have a static extension method in a nested and/or non-static class.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...