问题描述
我了解从另一个类继承的类可能会通过使用 new
关键字来隐藏属性.然而,这隐藏了该属性的特定实现,所以我可以看到它是如何使用的.
I understand that a class which inherits from another class may hide a property by using the new
keyword. This, however, is hiding a specific implementation of the property, so I can see how it could be used.
在实现其他接口的接口中隐藏成员是否有任何实际理由?例如考虑下面的例子.IChildInterface
实现 IParentInterface
,并隐藏 PropertyA
.
Is there any practical reason to hide members in interfaces which implement other interfaces? For example consider the example below. IChildInterface
implements IParentInterface
, and hides PropertyA
.
interface IParentInterface
{
string Name { get; set; }
int PropertyA { get; set; }
int PropertyB { get; set; }
}
interface IChildInterface : IParentInterface
{
int PropertyA { get; set; }
int PropertyC { get; set; }
}
推荐答案
是否有任何实际理由在实现其他接口的接口中隐藏成员?
Is there any practical reason to hide members in interfaces which implement other interfaces?
当然.BCL 本身使用此模式的事实表明该模式是实用的.例如:
Sure. The fact that the BCL itself uses this pattern is indicative that the pattern is practical. For example:
interface IEnumerable
{
IEnumerator GetEnumerator();
}
interface IEnumerable<T> : IEnumerable
{
new IEnumerator<T> GetEnumerator();
}
IEnumerable<T>
的设计者希望与 IEnumerable
向后兼容,但也希望确保每次使用 GetEnumerator
泛型接口称为泛型版本.在这种情况下,隐藏是适当的机制.
The designers of IEnumerable<T>
wished to be backwards-compatible with IEnumerable
but also wanted to ensure that every usage of GetEnumerator
on the generic interface called the generic version. Hiding is the appropriate mechanism in this case.
有关方法隐藏的一些细节的额外讨论,请参阅:
For some additional discussion on subtle points about method hiding, see:
http://blogs.msdn.com/b/ericlippert/archive/2008/05/21/method-hiding-apologia.aspx
这篇关于有没有理由在接口中隐藏继承的成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!