c# - 从它们扩展的类中使用扩展方法

标签 c# class extension-methods

<分区>

考虑这个类:

public class Thing {

    public string Color { get; set; }

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

}

我可以省略关键字 this因为ColorThing 的属性, 我在 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();
}

最佳答案

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.

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

当然,这并不能证明为什么以这种方式设计该功能 - 它只是证明编译器在正确性方面的行为。

关于c# - 从它们扩展的类中使用扩展方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18723224/

相关文章:

c# - Entity Framework 。需要帮助过滤结果

c# - 如何优雅地处理 winforms 应用程序中的休眠/ sleep 模式?

python - 使用Python分析文件中数据的类结构

c# - 常规方法的 Action/Func 扩展方法

c# - 不支持的重载用于查询运算符 'Distinct'

c# - 当应用程序关闭时,如何停止在 Monitor.Wait 上等待的 LongRunning 任务?

c# - 得到一个没有很多 if 语句的类

c++ - 类相互依赖

c# - 处理列表的扩展方法不起作用

c# - 扩展方法对子类不起作用?