为什么我不能为静态类创建扩展方法?

发布于 2024-08-24 00:33:50 字数 96 浏览 9 评论 0原文

当我尝试为 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

韶华倾负 2024-08-31 00:33:50

扩展方法在对象的实例上调用。

myObj.ExtensionMethod();

如果您有一个静态类,则无法拥有它的实例。因此,没有什么可以调用扩展方法。

Extension methods are called on an instance of an object.

myObj.ExtensionMethod();

If you have a static class, you can't have an instance of it. Therefore, there's nothing to call the extension method on.

内心激荡 2024-08-31 00:33:50

因为扩展方法在设计上必须采用该类的实例扩展作为其第一个参数。显然你不能传递 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.

柠檬色的秋千 2024-08-31 00:33:50

反过来说,如果您查看任何扩展方法的定义,第一个参数始终是调用该对象的实例,由 this 关键字证明。从逻辑上讲,此行为无法在静态类上运行,因为不存在实例。

扩展方法示例 - 查看第一个参数 this

public static class MyExtensions
{
    public static int WordCount(this String str)
    {
        return str.Split(new char[] { ' ', '.', '?' }, StringSplitOptions.RemoveEmptyEntries).Length;
    }
}   

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

public static class MyExtensions
{
    public static int WordCount(this String str)
    {
        return str.Split(new char[] { ' ', '.', '?' }, StringSplitOptions.RemoveEmptyEntries).Length;
    }
}   
人间不值得 2024-08-31 00:33:50

为什么我无法为静态类创建扩展方法?

因为 C# 开发团队尚未实现该功能。 F# 已选择尽管如此,还是要实现它。

扩展属性也是如此。 F# 拥有它们,Boo 从(至少)2006 年起就拥有它们

Why can’t I create extension methods for static classes?

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文