摘自Jeffrey的CLR via CSharp
接口方法默认是virtual and sealed. 意思是接口方法默认是没有继承的,这一点在你需要多态时需要注意。
Base b = new Base();
Derived d = new Derived();
b = new Derived();
// Calls Dispose by using b's type: "Base's Dispose"
b.Dispose();
((IDisposable)b).Dispose();//通过把b转化为接口可以实现调用子类方法
由于没有多态,上述Dispose调用的基类的方法。
源码如下:
class Program
{
static void Main(string[] args)
{
/************************* First Example *************************/
Base b = new Base();
// Calls Dispose by using b's type: "Base's Dispose"
//b.Dispose();
// Calls Dispose by using b's object's type: "Base's Dispose"
//((IDisposable)b).Dispose();
/************************* Second Example ************************/
Derived d = new Derived();
// Calls Dispose by using d's type: "Derived's Dispose"
//d.Dispose();
// Calls Dispose by using d's object's type: "Derived's Dispose"
//((IDisposable)d).Dispose();
/************************* Third Example *************************/
b = new Derived();
// Calls Dispose by using b's type: "Base's Dispose"
b.Dispose();
// Calls Dispose by using b's object's type: "Derived's Dispose"
((IDisposable)b).Dispose();
}
}
// This class is derived from Object and it implements IDisposable
internal class Base : IDisposable
{
// This method is implicitly sealed and cannot be overridden
public void Dispose()
{
Console.WriteLine("Base's Dispose");
}
}
// This class is derived from Base and it re-implements IDisposable
internal class Derived : Base, IDisposable
{
// This method cannot override Base's Dispose. 'new' is used to indicate
// that this method re-implements IDisposable's Dispose method
new public void Dispose()
{
Console.WriteLine("Derived's Dispose");
// NOTE: The next line shows how to call a base class's implementation (if desired)
// base.Dispose();
}
}
如果接口方法需要多态,源码可以改成如下:
internal class Base : IDisposable
{
// This method is implicitly sealed and cannot be overridden
public virtual void Dispose()
{
Console.WriteLine("Base's Dispose");
}
}
// This class is derived from Base and it re-implements IDisposable
internal class Derived : Base, IDisposable
{
// This method cannot override Base's Dispose. 'new' is used to indicate
// that this method re-implements IDisposable's Dispose method
public override void Dispose()
{
Console.WriteLine("Derived's Dispose");
// NOTE: The next line shows how to call a base class's implementation (if desired)
// base.Dispose();
}
}
真正需要思考的问题是为什么微软要把接口方法默认为不可以继承的?