我正在尝试打电话扩展方法在我自己的课程上,但无法编译。考虑以下代码行:
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();
}
}
基本上我是在界面上进行扩展。我不断收到此错误:
The name 'HelloWorld' does not exist in the current context
有人可以向我解释一下吗?当我进行演员表时,一切似乎都很好:
return ((Test)this).HelloWorld();
有什么解释吗?
The cast没有必要-this
部分是。所以这工作正常:
return this.HelloWorld();
第 7.6.5.2 节明确讨论了以下形式的方法调用
expr.identifier ( )
expr.identifier ( args )
expr.identifier < typeargs > ( )
expr.identifier < typeargs > ( args )
这个调用:
HelloWorld()
不是那种形式,因为不涉及任何表达。
我现在还不清楚why语言就是这样设计的(即为什么“隐式这一点”被排除在外),也许埃里克·利珀特(Eric Lippert)稍后会添加对此效果的答案。 (答案很可能是这样的:“因为规范、实现和测试需要很长时间,而收益相对较小。”)但是,这个答案至少表明 C# 编译器坚持规范。 ..
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)