如何调用从自己的类扩展方法而无需进行转换? [英] How to call an extension method from own class without casting?

查看:138
本文介绍了如何调用从自己的类扩展方法而无需进行转换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图调用的扩展方法的对我自己的类,但它无法编译。考虑code以下行:

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
{
}

public static class Extensions
{
    public static string HelloWorld(this IHelloWorld ext)
    {
        return "Hello world!";
    }
}

public class Test : IHelloWorld
{
    public string SaySomething()
    {
        return HelloWorld();
    }
}

基本上我扩展接口上。我不断收到此错误:

Basically I'm extending on the interface. I keep getting this error:

The name 'HelloWorld' does not exist in the current context

任何人都可以解释这样对我?当我做一个演员都觉得很好:

Can anybody explains this to me? When I do a cast all seems well:

收益率((测试)本).HelloWorld();

任何解释?

推荐答案

铸造的是没有必要的 - 在部分。因此,这正常工作:

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

return this.HelloWorld();

第7.6.5.2明确地谈到了形式的方法调用

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 )

此调用:

HelloWorld()

是这种形式不是,因为有没有涉及EX pression。

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

这不是不清楚我的为什么的语言是这样设计的(也就是为什么隐这种被排除在外),也许埃里克利珀将添加一个回答这个效果后。 (答案很可能是大致相同的,因为它会采取很长时间才能规格,实施和测试,相对较少的好处。)不过,这个回答至少说明了C#编译器是坚持规范。 ..

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...

这篇关于如何调用从自己的类扩展方法而无需进行转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆