我知道从另一个类继承的类可以使用 new
关键字隐藏属性。但是,这隐藏了该属性的特定实现,因此我可以了解如何使用它。
在实现其他接口(interface)的接口(interface)中隐藏成员是否有任何实际原因?例如考虑下面的例子。 IChildInterface
实现了IParentInterface
,并隐藏了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 本身使用此模式这一事实表明该模式是实用的。例如:
interface IEnumerable
{
IEnumerator GetEnumerator();
}
interface IEnumerable<T> : IEnumerable
{
new IEnumerator<T> GetEnumerator();
}
IEnumerable<T>
的设计师希望向后兼容 IEnumerable
但也想确保每次使用 GetEnumerator
在通用接口(interface)上称为通用版本。在这种情况下,隐藏是合适的机制。
有关方法隐藏的细微之处的一些额外讨论,请参阅:
http://blogs.msdn.com/b/ericlippert/archive/2008/05/21/method-hiding-apologia.aspx
关于c# - 是否有理由在界面中隐藏继承的成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3570561/