加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 使用扩展方法从类中扩展

发布时间:2020-12-16 00:09:13 所属栏目:百科 来源:网络整理
导读:参见英文答案 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()
参见英文答案 > 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();
}

解决方法

I can omit this when referencing properties and methods,so why can’t I do this…?

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

In a method invocation (7.5.5.1) of one of the forms

expr . identifier ( )
expr . identifier ( args )
expr . identifier < typeargs > ( )
expr . identifier < typeargs > ( args )

if the normal processing of the invocation finds no applicable methods,an attempt is made to process the construct as an extension method invocation.

如果没有这个,你的调用将不会是那种形式,因此规范的这一部分将不适用.

当然,这并不能说明为什么要以这种方式设计特征 – 这是编译器在正确性方面的行为的理由.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读