如何检测是否虚方法是在C#重写 [英] How to detect if virtual method is overridden in c#

查看:170
本文介绍了如何检测是否虚方法是在C#重写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能确定一个虚方法已被重写:

Is it possible to determine if a virtual method has been overridden:

class ABase {

  public void DoSomething(object p)
  {
    p.Process();
    if( /* DoSomethingExtra is implemented */ )
      DoSomethingExtra(p);
  }
  public virtual void DoSomethingExtra(object p) { }

}

class ADerived {
  public override void DoSomethingExtra(object p)
  {
    p.ProcessMore();
  }
}



我意识到,这个例子似乎是愚蠢的(如:你为什么不'T你只需要调用DoSomethingExtra(),因为它不会做任何事情)。我向你保证,我对这个合法的情况下。任何想法?

I realize that this example seems stupid (e.g. why don't you just call DoSomethingExtra() since it doesn't do anything). I assure you I have a legitimate case for this. Any ideas?

推荐答案

检查了这一点的如果检测的方法是使用反射(C#)

反射将被覆盖只有这样,才能在运行时做到这一点。这应该有一个健康警告但是,它应被视为从面向对象的角度来看一个非常糟糕的主意(TM)。基类,一般不应知道也不关心如何派生类中实现。

Reflection would be the only way to do this at runtime. This should come with a health warning however, it should be considered a Very Bad Idea (tm) from an OOP perspective. A base class should not generally know or care how a derived class is implemented.

这篇关于如何检测是否虚方法是在C#重写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆