为什么我不能为静态类创建扩展方法?
当我尝试为 File 类创建扩展方法时,收到一条错误消息,告诉我无法执行此操作,因为该类是静态的。但是,我不明白为什么这会停止扩展方法的创建,这有什么含义?
谢谢
When I try to create an extension method for the File class, I get an error telling me that I cannot do this because the class is static. However, I don't see why this stops the creation of an extension method, what implication is there?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
扩展方法在对象的实例上调用。
如果您有一个静态类,则无法拥有它的实例。因此,没有什么可以调用扩展方法。
Extension methods are called on an instance of an object.
If you have a static class, you can't have an instance of it. Therefore, there's nothing to call the extension method on.
因为扩展方法在设计上必须采用该类的实例扩展作为其第一个参数。显然你不能传递 File 的实例,因为它是静态类并且不能有实例。
Because an extension method by design must take an instance of the class it is extending as its first parameter. And obviously you can't pass an instance of File because it is a static class and cannot have instances.
反过来说,如果您查看任何扩展方法的定义,第一个参数始终是调用该对象的实例,由
this
关键字证明。从逻辑上讲,此行为无法在静态类上运行,因为不存在实例。扩展方法示例 - 查看第一个参数 this
Stated in reverse, if you look at the definition of any extension method, the first parameter is always the instance of the object upon which it is called evidenced by the
this
keyword. Logically this behaviour cannot work on a static class because there is no instance present.Sample of an extension method - see first param this
因为 C# 开发团队尚未实现该功能。 F# 已选择尽管如此,还是要实现它。
扩展属性也是如此。 F# 拥有它们,Boo 从(至少)2006 年起就拥有它们。
Because the C# dev team didn't implement that feature (yet). F# has chosen to implement it though.
Same thing for extension properties. F# has them and Boo has had them since (at least) 2006.