从理论上讲,接口实现和类继承都解决了同样的问题:它们允许您在类型之间定义子类型关系。
那么为什么在C#中我们需要同时拥有它们?为什么我们需要接口?难道我们不能像在C++中一样将接口定义为抽象类吗?
如果B和C都以不同的方式实现A.DoSomething(),那么D应该继承哪个实现呢?这是一个难题,Java和C#的设计者决定通过仅允许多重继承特殊基类型(它们不包括任何实现)来避免这个问题。他们决定将这些特殊的基类型称为接口。interface I1
{
void M() { Console.WriteLine("I1.M"); } // default method
}
interface I2
{
void M() { Console.WriteLine("I2.M"); } // default method
}
class C : I1, I2 { }
class Program
{
static void Main(string[] args)
{
// c, i1 and i2 reference the same object
C c = new C();
I1 i1 = c;
I2 i2 = c;
i1.M(); // prints "I1.M"
i2.M(); // prints "I2.M"
c.M(); // compile error: class 'C' does not contain a member 'M'
}
}