开发者

Is is possible to override a hidden method?

Say I have the following hierarchy:

public cla开发者_如何学Goss MyClass
{
  protected virtual void Method() { ... }
}

public class MySubClass : MyClass
{
  public new virtual void Method() { ... }
}

public class MySubSubClass : MySubClass
{
  // how do I reference the protected Method() to override it?
}

Is it possible to override the implementation of the protected Method() so that invocations from other methods defined in MyClass are dispatched to an implementation in MySubSubClass?

If not possible, it'd be nice to be enlightened as to why.


If you're attempting to override the version of Method defined in MyClass then the answer is you cannot. The definition in MySubClass hides this implementation from you and it's not possible for you to further override it.


if you mark your hidden method as also being virtual you can override the hidden method:

public new virtual void Method()


Yes. You can use "new" keyword to reintroduce any method you want. From that point on, every call to the the "newed" method will be addressed to the new implementation.

In this case, any call to Method() originated from MyClass will use the MySubSubClass implementation as long as the object in question is of type MySubSubClass


As @Jared said, you cannot. I can only assume that you're trying to avoid using new again because you want proper virtual handling. The only way you're going to manage this is by getting rid of the public new version of Method() and naming it something else. new completely hides any version of the method you're redeclaring that may exist in ancestor objects.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜