One use I sometimes have for the new keyword is for 'poor mans property covariance' in a parallell inheritance tree. Consider this example:
public interface IDependency
{
}
public interface ConcreteDependency1 : IDependency
{
}
public class Base
{
protected Base(IDependency dependency)
{
MyDependency = dependency;
}
protected IDependency MyDependency {get; private set;}
}
public class Derived1 : Base // Derived1 depends on ConcreteDependency1
{
public Derived1(ConcreteDependency1 dependency) : base(dependency) {}
// the new keyword allows to define a property in the derived class
// that casts the base type to the correct concrete type
private new ConcreteDependency1 MyDependency {get {return (ConcreteDependency1)base.MyDependency;}}
}
The inheritance tree Derived1 : Base has a 'parallell dependency' on ConcreteDependency1 : IDependency'. In the derived class, I know that MyDependency is of type ConcreteDependency1, therefore I can hide the property getter from the base class using the new keyword.
EDIT: see also this blog post by Eric Lippert for a good explanation of the new keyword.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…