附加的代码按预期工作,它打印“某样东西!”,但它是定义的行为(从“显式”方法调用“normal”方法)吗?
我搜索了“显式接口调用方法/函数”的各种组合,但我所能找到的只是关于隐式接口函数和显式定义接口函数之间的区别以及如何调用显式定义函数的示例。
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();
}
};发布于 2022-06-15 11:40:51
无论您的代码是如何工作的,您的代码都将具有相同的输出。我建议使用next来更清楚地理解:
class Something : ISomething
{
private void DoSomething()
{
Console.WriteLine("Something!");
}
void ISomething.DoSomething()
{
Console.WriteLine("Explicit Something!");
}
};它将为您的Explicit Something!打印Main。至于为什么这两种实现-作为草案C# 7.0规范州
不可能通过方法调用、属性访问、事件访问或索引器访问中的限定接口成员名访问显式接口成员实现。--一个显式接口成员实现只能通过接口实例访问,在这种情况下,只需通过其成员名称来引用。
因此,原始ISomething.DoSomething()实现中的ISomething.DoSomething()调用是对Something.DoSomething()的调用,而不是对ISomething.DoSomething()的调用。ISomething.DoSomething()无法访问,因为它需要一个接口实例。如果将ISomething.DoSomething重命名为ISomething.DoSomething1,您将看到在ISomething.DoSomething1调用中无法访问它,除非您将this转换为接口:
interface ISomething
{
void DoSomething1();
}
class Something : ISomething
{
public void DoSomething()
{
Console.WriteLine("Something!");
}
void ISomething.DoSomething1()
{
// DoSomething1(); // The name 'DoSomething1' does not exist in the current context
// ((ISomething)this).DoSomething1(); // will obviously end in SO
Console.WriteLine("ISomething.DoSomething1!");
}
}也可以是有用的界面映射部分:
接口映射算法的显著含义是:
https://stackoverflow.com/questions/72630363
复制相似问题