Eri*_*tas 13 .net c# polymorphism interface
我知道从另一个类继承的类可能会使用new关键字隐藏属性.但是,这隐藏了属性的特定实现,因此我可以看到它是如何使用的.
是否有任何实际的理由在实现其他接口的接口中隐藏成员?例如,考虑以下示例.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; }
}
Run Code Online (Sandbox Code Playgroud)
Eri*_*ert 23
是否有任何实际的理由在实现其他接口的接口中隐藏成员?
当然.BCL本身使用这种模式的事实表明该模式是实用的.例如:
interface IEnumerable
{
IEnumerator GetEnumerator();
}
interface IEnumerable<T> : IEnumerable
{
new IEnumerator<T> GetEnumerator();
}
Run Code Online (Sandbox Code Playgroud)
设计者IEnumerable<T>希望能够向后兼容,IEnumerable但也希望确保GetEnumerator通用接口上的每种用法都称为通用版本.在这种情况下,隐藏是适当的机制.
关于方法隐藏的细微点的一些额外讨论,请参阅:
http://blogs.msdn.com/b/ericlippert/archive/2008/05/21/method-hiding-apologia.aspx
我发现隐藏基本成员有用的一个案例是当你有一个基本接口,它在属性上公开一个getter但是派生接口想要暴露一个setter:
public interface IBase
{
int MyProperty { get; }
}
public interface IDerive : IBase
{
// you need to specify the getter here too
new int MyProperty { get; set; }
}
Run Code Online (Sandbox Code Playgroud)