作者:此女我很爱_484 | 来源:互联网 | 2022-11-02 13:16
我正在研究接口,并遇到了一些奇怪的接口问题,其中的规则是我们必须实现公共接口方法。但是在这个例子中没有。
我尝试了从经验中学到的知识,发现的答案确实违反了规则。
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()
为什么会这样呢?
1> Johnny..:
它不是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
您可能希望通过引用文档中的相关部分进行详细说明。