在他们扩展的类中使用扩展方法

BG1*_*100 3 c# extension-methods class

考虑这个课程:

public class Thing {

    public string Color { get; set; }

    public bool IsBlue() {
        return this.Color == "Blue";   // redundant "this"
    }

}
Run Code Online (Sandbox Code Playgroud)

我可以省略关键字,this因为它Color是一个属性Thing,我正在编码Thing.

如果我现在创建一个扩展方法:

public static class ThingExtensions {

    public static bool TestForBlue(this Thing t) {
        return t.Color == "Blue";
    }

}
Run Code Online (Sandbox Code Playgroud)

我现在可以将我的IsBlue方法更改为:

public class Thing {

    public string Color { get; set; }

    public bool IsBlue() {
        return this.TestForBlue();   // "this" is now required
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,我现在需要包含this关键字.

this在引用属性和方法时我可以省略,为什么我不能这样做......?

public bool IsBlue() {
    return TestForBlue();
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 11

在引用属性和方法时我可以省略它,为什么我不能这样做......?

它只是扩展方法调用的一部分,基本上.C#规范(扩展方法调用)的第7.6.5.2节开始:

在其中一个表单的方法调用(7.5.5.1)中

expr.标识符 ( )
expr.标识符 ( args )
expr.标识符 < typeargs > ( )
expr.标识符 < 类型 > ( args )

如果调用的正常处理找不到适用的方法,则尝试将该构造作为扩展方法调用进行处理.

没有this,您的调用将不是那种形式,因此该规范的部分将不适用.

当然,这并不能说明为什么要以这种方式设计该特征- 这是编译器在正确性方面的行为的理由.