Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
375 views
in Technique[技术] by (71.8m points)

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

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 derived class, then it cannot be overridden. Then it is the same as creating a fresh method (other than the one mentioned in the base class) with a different name.

Is there any specific reason to use the new keyword?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...