method hiding in c# with a valid example. why is it implemented in the framework? what is the Real world advantage?

前端 未结 6 1068
春和景丽
春和景丽 2020-12-05 19:53

Can anyone explain the actual use of method hiding in C# with a valid example ?

If the method is defined using the new keyword in the d

6条回答
  •  北荒
    北荒 (楼主)
    2020-12-05 20:27

    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.

提交回复
热议问题