问题描述
为什么扩展方法要求声明类是静态的?
Why do extension methods require the declaring class to be static? Is it a compiler requirement?
推荐答案
这是语言规范中C#4规范的10.6.9节所规定的:
It's dictated in the language specification, section 10.6.9 of the C# 4 spec:
我不清楚为什么所有这些限制都是必需的-除了可能简化编译器(和语言规范)。我可以理解为什么将其限制为非通用类型是有意义的,但是我无法立即了解为什么它们必须是非嵌套和静态的。我怀疑,如果您不必担心当前类型中包含的类型等,它将使查找规则变得相当简单,但是我敢说这是可能的。
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.
编辑:明确地说,我并不是在暗示这样做会将实例方法用作扩展方法很有意义-我建议在嵌套和/或非静态类中使用静态扩展方法是有意义的。
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.
这篇关于扩展方法要求声明类为静态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!