简体   繁体   English

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

[英]Why can't I create extension methods for static classes?

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. 当我尝试为File类创建一个扩展方法时,我收到一个错误,告诉我我不能这样做,因为该类是静态的。 However, I don't see why this stops the creation of an extension method, what implication is there? 但是,我不明白为什么这会停止创建扩展方法,有什么含义?

Thanks 谢谢

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. 因此,没有什么可以调用扩展方法。

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. 显然你不能传递File的实例,因为它是一个静态类,不能有实例。

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. 换句话说,如果查看任何扩展方法定义 ,第一个参数始终是this关键字所调用的对象的实例。 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;
    }
}   

Why can't I create extension methods for static classes? 为什么我不能为静态类创建扩展方法?

Because the C# dev team didn't implement that feature (yet). 因为C#dev团队尚未实现该功能。 F# has chosen to implement it though. F#已选择实现它

Same thing for extension properties. 扩展属性也是一样的。 F# has them and Boo has had them since (at least) 2006 . 自从(至少)2006年以来, F#拥有它们并且Boo拥有它们

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM