考虑以下这个类:
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();
}
this
,只是我对编码的整洁性有强迫症,这个关键字让我很烦恼!!! - BG100ThingExtensions.TestForBlue(this)
。 - Olivier Jacot-Descombes