使用类中的扩展方法进行扩展

BG100

考虑此类:

public class Thing {

    public string Color { get; set; }

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

}

我可以省略关键字,this因为它Color是的属性Thing,并且我在内进行编码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)中

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

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

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

当然,这不是为什么要以这种方式设计功能的理由-这是根据正确性来证明编译器行为的理由。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章