c# – 使用扩展方法从类中扩展
参见英文答案 >
Why is the ‘this’ keyword required to call an extension method from within the extended class????????????????????????????????????6个
考虑这个课程: 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关键字. 在引用属性和方法时我可以省略它,为什么我不能这样做……? public bool IsBlue() { return TestForBlue(); } 解决方法
它只是扩展方法调用的一部分,基本上. C#规范(扩展方法调用)的第7.6.5.2节开始:
如果没有这个,你的调用将不会是那种形式,因此规范的这一部分将不适用. 当然,这并不能说明为什么要以这种方式设计特征 – 这是编译器在正确性方面的行为的理由. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |