J B*_*vin 2 c# inheritance interface-implementation diamond-problem
如果一个类从两个单独的接口实现一个接口,它的行为是否与仅实现一次相同?
例子:
public interface IAnimal { /* ... */ }
public interface IFullAnimal : IAnimal { /* ... */ }
public interface IBear : IAnimal { /* ... */ }
public interface IFullBear : IBear, IFullAnimal { /* ... */ }
// and implementing IFullBear:
public class FullBear : IFullBear { /* ... */ }
Run Code Online (Sandbox Code Playgroud)
上面,FullBear实现了IAnimal从IFullAnimal和IBear到IFullBear。这是否会引入有关 IAnimal 实现的任何奇怪行为,因为两者IFullAnimal都IBear没有提供有关实现的任何信息IAnimal(因为该语言不允许这样做)。
不,这是一种非常常见且无害的情况。System.Collections.Generic命名空间是类似“冗余”接口声明的一个很好的例子:
public class List<T> : IList<T>,
System.Collections.IList,
IReadOnlyList<T>
Run Code Online (Sandbox Code Playgroud)
显然两者IList<T>都实施了,世界还没有结束。IReadOnlyList<T>IEnumerable<T>
不要将此与接口重新实现混淆,后者确实会改变行为:
interface IFoo
{
void Foo();
}
class Base: IFoo
{
public void Foo() { Console.WriteLine("Base Foo!");
}
class Derived: Base { }
class DerivedWithATwist: Base, IFoo //redeclares interface
{
void IFoo.Foo() { Console.WriteLine("Derived Foo!");
}
Run Code Online (Sandbox Code Playgroud)
现在,
IFoo foo = new Base();
IFoo derived = new Derived();
IFoo derivedWithATwist = new DerivedWithATwist();
foo.Foo(); //Base Foo!
derived.Foo(); //Base Foo!
derivedWithATwist.Foo(); //Derived Foo!
(derivedWithATwist as Base).Foo(); //Base Foo! !!!
Run Code Online (Sandbox Code Playgroud)