为什么接受实现私有接口方法?

Ron*_*ano 1 c# interface

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

我尝试了从经验中学到的知识,发现的答案确实违反了规则。

    public interface DropV1
    {
        void Ship();
    }

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

    }
Run Code Online (Sandbox Code Playgroud)

我原以为10亿%的实施将是:

public void DropV1.Ship()
public void DropV2.Ship()
Run Code Online (Sandbox Code Playgroud)

为什么会这样呢?

Joh*_*nny 6

它不是private所谓的显式接口实现。在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
Run Code Online (Sandbox Code Playgroud)

  • 您可能希望通过引用文档中的相关部分进行详细说明。 (2认同)