如果一个类从两个单独的接口实现一个接口,它的行为是否与仅实现一次相同?
Example:
public interface IAnimal { /* ... */ }
public interface IFullAnimal : IAnimal { /* ... */ }
public interface IBear : IAnimal { /* ... */ }
public interface IFullBear : IBear, IFullAnimal { /* ... */ }
// and implementing IFullBear:
public class FullBear : IFullBear { /* ... */ }
Above, FullBear
实施IAnimal
来自两者IFullAnimal
and IBear
通过IFullBear
。这是否会引入有关 IAnimal 实现的任何奇怪行为因为两者IFullAnimal
and IBear
不提供任何有关实施的信息IAnimal
(因为语言不允许这样做)。
不,这是一种非常常见且无害的情况。System.Collections.Generic
命名空间是类似“冗余”接口声明的一个很好的例子:
public class List<T> : IList<T>,
System.Collections.IList,
IReadOnlyList<T>
Both IList<T>
and 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!");
}
And now,
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! !!!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)