Kee*_*ker 10 .net c# extension-methods .net-4.0 c#-4.0
我试图在我自己的类上调用扩展方法,但它无法编译.请考虑以下代码行:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
基本上我正在扩展界面.我一直收到这个错误:
The name 'HelloWorld' does not exist in the current context
Run Code Online (Sandbox Code Playgroud)
有人可以向我解释一下吗?当我做一个演员表似乎很好:
return ((Test)this).HelloWorld();
有什么解释吗?
Jon*_*eet 21
该投是没有必要的-的this一部分.所以这很好用:
return this.HelloWorld();
Run Code Online (Sandbox Code Playgroud)
第7.6.5.2节明确地讨论了表单的方法调用
expr.identifier ( )
expr.identifier ( args )
expr.identifier < typeargs > ( )
expr.identifier < typeargs > ( args )
Run Code Online (Sandbox Code Playgroud)
这个调用:
HelloWorld()
Run Code Online (Sandbox Code Playgroud)
不是那种形式,因为没有表达.
我不能立即清楚为什么语言是这样设计的(即为什么"隐含的这个"被排除在外),也许Eric Lippert将在后面添加一个答案.(答案很可能是"因为它需要花费很长时间才能进行规范,实现和测试,但收益相对较小.")但是,这个答案至少表明C#编译器坚持规范. ..