在类中使用扩展方法,它们扩展
考虑这个课程:
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 。 标识符<
typeargs>
(
args)
如果调用的正常处理找不到适用的方法,则尝试将该构造作为扩展方法调用进行处理。
如果没有this
,你的调用将不会是那种forms,因此规范的这一部分将不适用。
当然,这并不能说明为什么要以这种方式设计该特征 - 这是编译器在正确性方面的行为的理由。
因为你需要调用它将要调用的扩展方法类型 ,因为Extension被定义为Thing , 对象需要调用自身以及为其定义的静态方法 。