How to call an extension method from own class without casting?

后端 未结 3 1423
死守一世寂寞
死守一世寂寞 2021-02-14 06:46

I\'m trying to call an extension method on my own class, but it fails to compile. Consider the following lines of code:

public interface IHelloWorld
{
}         


        
3条回答
  •  天涯浪人
    2021-02-14 07:30

    The cast isn't necessary - the this part is. So this works fine:

    return this.HelloWorld();
    

    Section 7.6.5.2 explicitly talks about method invocations of the form

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

    This invocation:

    HelloWorld()
    

    isn't of that form, as there's no expression involved.

    It's not immediately clear to me why the language was designed that way (i.e. why the "implicit this" was excluded) and maybe Eric Lippert will add an answer to that effect later. (The answer may well be along the lines of "because it would have taken a long time to spec, implement and test, for relatively little benefit.") However, this answer at least shows that the C# compiler is sticking to the spec...

提交回复
热议问题