使用它们扩展的类中的扩展方法

本文关键字:扩展 方法 | 更新日期: 2023-09-27 18:30:52

考虑这个类:

public class Thing {
    public string Color { get; set; }
    public bool IsBlue() {
        return this.Color == "Blue";   // redundant "this"
    }
}

我可以省略关键字this因为ColorThing的属性,并且我在Thing内编码。

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

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

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

public class Thing {
    public string Color { get; set; }
    public bool IsBlue() {
        return this.TestForBlue();   // "this" is now required
    }
}

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

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

public bool IsBlue() {
    return TestForBlue();
}

使用它们扩展的类中的扩展方法

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

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

在方法调用 (7.5.5.1) 中,其中一种形式

埃克尔 .标识符 ( ) 埃克尔 .标识符 (参数 )
埃克尔 .标识符 < typeargs > ( )
埃克尔 .标识符 < typeargs > ( args )

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

如果没有this,您的调用将不会是这种形式,因此规范的该部分将不适用。

当然,这并不是为什么以这种方式设计该功能的理由 - 这是编译器在正确性方面行为的理由。

因为您需要调用它将调用哪种扩展方法类型,因此由于 Extension 被定义为 Thing,因此对象需要调用自身和为其定义的静态方法