从具有相同名称的显式接口函数调用类函数
随附的代码按预期工作,它打印“某物!”, 但是定义行为(从“显式”方法调用“正常”方法)?
我搜索了“显式接口调用方法/函数”的各种组合,但是我所能找到的只是有关隐式和明确定义的接口函数之间差异的示例,以及如何调用明确定义的函数。
interface ISomething
{
void DoSomething();
}
class Something : ISomething
{
private void DoSomething()
{
Console.WriteLine("Something!");
}
void ISomething.DoSomething()
{
DoSomething();
}
public static void Main()
{
ISomething thing = new Something();
thing.DoSomething();
}
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
无论事情如何工作,您的代码都将具有相同的输出。我建议使用下一个以更清楚地理解:
哪些将打印出
明确的东西!
为您的main
。至于为什么两个实施 - 作为C#7.0规格草案 state :因此代码> this 到接口:
dosomething()
在原始isomething.dosomething()
实现中呼叫sosity.dosomething()
,而不是.dosomething()
。isomething.dosomething()
是不可访问的原因,因为它需要接口实例。如果您重命名isomething.dosothing
为isomething.dosomething1
,您会看到它在isomething> isomething.dosomething.dosomething.dosomething 1
call除非施放也可以很有用接口映射部分:
Your code will have the same output no matter how things work. I suggest using next for clearer understanding:
Which will print
Explicit Something!
for yourMain
. As for why for both implementations - as draft C# 7.0 specification states:So
DoSomething()
call in originalISomething.DoSomething()
implementation is call to theSomething.DoSomething()
and not toISomething.DoSomething()
.ISomething.DoSomething()
is no accessible cause it requires an interface instance. If you renameISomething.DoSomething
to for exampleISomething.DoSomething1
you will see that it is not accessible insideISomething.DoSomething1
call unless you castthis
to interface:Also can be useful interface mapping section: