接口实现的继承机制
一个类继承了它的基类提供的接口的实现:
注意:如果不显式地重新实现接口,派生类就无法改变从基类中继承来的接口映射。
using System;
interface IControl
{
void Paint();
}
class Control:IControl
{
public void Paint()
{
Console.WriteLine("Control invoke!");
}
}
class TextBox:Control
{
new public void Paint()
{
Console.WriteLine("TextBox invoke!");
}
}
class Invoke
{
public static void Main()
{
Control c = new Control();
TextBox tb = new TextBox();
IControl ic = c;
IControl it = tb;
c.Paint(); // invokes Control.Paint();
tb.Paint(); // invokes TextBox.Paint();
ic.Paint(); // invokes Control.Paint();
it.Paint(); // invokes Control.Paint();
}
}
interface IControl
{
void Paint();
}
class Control:IControl
{
public void Paint()
{
Console.WriteLine("Control invoke!");
}
}
class TextBox:Control
{
new public void Paint()
{
Console.WriteLine("TextBox invoke!");
}
}
class Invoke
{
public static void Main()
{
Control c = new Control();
TextBox tb = new TextBox();
IControl ic = c;
IControl it = tb;
c.Paint(); // invokes Control.Paint();
tb.Paint(); // invokes TextBox.Paint();
ic.Paint(); // invokes Control.Paint();
it.Paint(); // invokes Control.Paint();
}
}
但是,当一个interface方法被映射到类中的一个虚方法时,派生类就可以重载这个虚方法,并且改变这个接口的实现:
interface IControl
{
void Paint();
}
class Control:IControl
{
public virtual void Paint()
{
}
}
class TextBox:Control
{
public override void Paint()
{
}
}
{
void Paint();
}
class Control:IControl
{
public virtual void Paint()
{
}
}
class TextBox:Control
{
public override void Paint()
{
}
}
代码效果:
Control c = new Control();
TextBox tb = new TextBox();
IControl ic = c;
IControl it = tb;
c.Paint(); // 调用Control.Paint();
tb.Paint(); // 调用TextBox.Paint();
ic.Paint(); // 调用Control.Paint();
it.Paint(); // 调用TextBox.Paint();
因为显式说明的接口成员不能被声明为虚的,因此无法重载显式说明的接口实现:
注意:这时最好采用显式说明的接口实现来调用另一个方法,这个被调用的方法可以被声明为虚的,允许被派生类重载。
interface IControl
{
void Paint();
}
class Control:IControl
{
void IControl.Paint()
{
PaintControl();
}
protected virtual void PaintControl()
{
}
}
class TextBox:Control
{
protected override void PaintControl()
{
}
}
{
void Paint();
}
class Control:IControl
{
void IControl.Paint()
{
PaintControl();
}
protected virtual void PaintControl()
{
}
}
class TextBox:Control
{
protected override void PaintControl()
{
}
}
这里,从Control中派生的类可以通过重载PaintControl方法来具体实现IControl.Paint。
引用自:
http://www2.cnblogs.com/netfork/archive/2004/03/23/3930.html