可能的重复:
C#:接口 - 隐式和显式实现
隐式与显式接口实现
你好
谁能解释一下隐式接口和显式接口之间的区别是什么?
谢谢!
当您显式实现接口时,该接口上的方法仅在对象被引用为接口时才可见:
public interface IFoo
{
void Bar();
}
public interface IWhatever
{
void Method();
}
public class MyClass : IFoo, IWhatever
{
public void IFoo.Bar() //Explicit implementation
{
}
public void Method() //standard implementation
{
}
}
如果您的代码中的某个地方引用了此对象:
MyClass mc = new MyClass();
mc.Bar(); //will not compile
IFoo mc = new MyClass();
mc.Bar(); //will compile
对于标准实现,如何引用对象并不重要:
MyClass mc = new MyClass();
mc.Method(); //compiles just fine
隐式接口实现是您拥有具有相同接口签名的方法。
显式接口实现是您显式声明该方法属于哪个接口的地方。
interface I1
{
void implicitExample();
}
interface I2
{
void explicitExample();
}
class C : I1, I2
{
void implicitExample()
{
Console.WriteLine("I1.implicitExample()");
}
void I2.explicitExample()
{
Console.WriteLine("I2.explicitExample()");
}
}
MSDN:隐式和显式接口实现
显式仅表示您指定接口,隐式表示您不指定。
例如:
interface A
{
void A();
}
interface B
{
void A();
}
class Imp : A
{
public void A() // Implicit interface implementation
{
}
}
class Imp2 : A, B
{
public void A.A() // Explicit interface implementation
{
}
public void B.A() // Explicit interface implementation
{
}
}
另外,如果您想知道为什么存在显式实现,那是因为您可以从多个接口实现相同的方法(名称和签名);那么如果你需要不同的功能,或者只是返回类型不同,你不能通过简单的重载来实现。那么你将不得不使用显式实现。一个例子是List<T>
实现IEnumerable
andIEnumerable<T>
并且两者都具有GetEnumerator()
但具有不同的返回值。