首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从同名显式接口函数调用类函数

从同名显式接口函数调用类函数
EN

Stack Overflow用户
提问于 2022-06-15 11:15:33
回答 1查看 38关注 0票数 0

附加的代码按预期工作,它打印“某样东西!”,但它是定义的行为(从“显式”方法调用“normal”方法)吗?

我搜索了“显式接口调用方法/函数”的各种组合,但我所能找到的只是关于隐式接口函数和显式定义接口函数之间的区别以及如何调用显式定义函数的示例。

代码语言:javascript
复制
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();
    }
};
EN

回答 1

Stack Overflow用户

发布于 2022-06-15 11:40:51

无论您的代码是如何工作的,您的代码都将具有相同的输出。我建议使用next来更清楚地理解:

代码语言:javascript
复制
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转换为接口:

代码语言:javascript
复制
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!");
    }
}

也可以是有用的界面映射部分:

接口映射算法的显著含义是:

  • 在确定实现接口成员的类或结构成员时,显式接口成员实现优先于同一类或结构中的其他成员。
  • 非公共成员和静态成员都不参与接口映射。
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72630363

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档