扩展方法要求声明类为静态 [英] Extension methods require declaring class to be static

查看:80
本文介绍了扩展方法要求声明类为静态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么扩展方法要求声明类是静态的?

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:


当方法
的第一个参数包含this修饰符时,该
方法被称为扩展名
方法。扩展方法只能在非通用的,非嵌套的
静态类中声明
。扩展方法
的第一个参数除此之外不能有
修饰符,并且
参数类型不能是指针
类型。

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.

编辑:明确地说,我并不是在暗示这样做会将实例方法用作扩展方法很有意义-我建议在嵌套和/或非静态类中使用静态扩展方法是有意义的。

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.

这篇关于扩展方法要求声明类为静态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆