【问题标题】:Why implementing an interface method private is accepted? [duplicate]为什么接受实现接口方法私有? [复制]
【发布时间】:2019-08-19 09:12:03
【问题描述】:

我正在研究接口并且遇到了一些奇怪的接口东西,其中规则是我们必须实现一个接口方法 public。但在这个例子中没有。

我已经尝试了我从经验中学到的东西,我找到的答案确实违反了规则。

    public interface DropV1
    {
        void Ship();
    }

    public interface DropV2
    {
        void Ship();
    }
    //accepted by the editor
    class DropShipping : DropV1, DropV2
    {
        void DropV1.Ship() { }
        void DropV2.Ship() { }

    }

我预计 10 亿% 的实施将是:

public void DropV1.Ship()
public void DropV2.Ship()

为什么会这样?

【问题讨论】:

  • 那么问题是这样的,好吧,让我直接使用这个类:var ds = new DropShipping(); ds.Ship(); 现在应该发生什么?这应该调用这两种方法中的哪一种?
  • @LasseVågsætherKarlsen 两者都不是。 Visual Studio intellesense 不显示这两种方法。
  • 当然,如果语言支持它,Visual Studio 也应该支持,我不是在问当前的 IDE 或编译器会做什么,我是在问你认为它应该做什么。
  • @LasseVågsætherKarlsen 好的。我要回到我还没有阅读我的问题的答案的时候。我真的不知道会发生什么,因为我会对它会调用什么感到困惑,因为它们在类中具有相同的方法名称。
  • 这就是他们不能那样做的原因。您不能有多个具有相同签名的方法。显式实现方法是最好的方法,因为您可以有一个公共方法,并且每个接口有一个显式实现,因为没有混淆。

标签: c# interface


【解决方案1】:

它不是private,它被称为explicit interface implementation。在interface 中,所有方法根据定义都是public,因此您不需要public 关键字(即使您想要也不能在这里使用它)。值得一提的是,当显式实现 interface 方法时,只能通过 interface 实例使用,而不能通过 class 实例使用:

public class SampleClass : IControl
{
    void IControl.Paint()
    {
        System.Console.WriteLine("IControl.Paint");
    }
}

IControl ctrl = new SampleClass();
ctrl.Paint(); //possible

SampleClass ctrl = new SampleClass();
ctrl.Paint(); //not possible

var ctrl = new SampleClass();
ctrl.Paint(); //not possible

((IControl) new SampleClass()).Paint(); //possible

【讨论】:

  • 您可能想通过引用文档中的相关部分来详细说明。
  • 也可以投射到界面 - ((IControl) new SampleClass()).Paint()
  • @stuartd 谢谢,也包括在内。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-07
  • 1970-01-01
  • 2013-01-20
  • 2017-01-12
  • 2012-07-20
  • 2021-01-19
相关资源
最近更新 更多