是否可以判断派生类中是否已重写.NET虚拟方法? [英] Is it possible to tell if a .NET virtual method has been overriden in a derived class?

查看:37
本文介绍了是否可以判断派生类中是否已重写.NET虚拟方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问这个问题的举动表明我对这个问题的解决方法是不正确的,因此我对直接解决该问题的答案以及对我正在做的事情采取更清洁方法的回答感兴趣.

The very act of asking this question suggests that my approach to this problem is incorrect, so I'm interested in answers which address the question directly, as well as answers which suggest a cleaner approach to what I'm doing.

请考虑一个基类,该基类提供一组标准的服务和功能以及围绕这些功能的一些结构.通过隐喻的方式,让我们考虑以下示例类:

Consider a base class which provides a standard set of services and functionalities, as well as some structure around those. By way of metaphor, let's consider the following example class:

public class ExampleBase
{
  public void Main()
  {
    // Do something
    PreValidate(); // Extensibility point for derived classes
    // Do something else
    PostValidate(); // Extensibility point for derived classes
    // Do something else 
  }

  protected virtual void PreValidate()
  {
  }

  protected virtual void PostValidate()
  {
  }
}

派生类现在可以重写这些虚拟方法以提供一些自定义逻辑.

The derived class can now override these virtual methods to provide some custom logic.

这是一个问题:基类是否有可能在运行时发现派生类是否具有重写这些虚拟方法之一的自由,即之前调用虚拟方法?

Here is the question: Is it possible for the base class to discover at runtime if the derived class has taken the liberty of overriding one of these virtual methods, before invoking the virtual method?

(如果在调用该方法后 知道了这个问题的答案,那么您可以用设置私有标志的方法替换基类中的空方法,这将表示该方法没有被覆盖.但是,如果派生类在其覆盖的实现中调用 base.PreValidate(),则可能会被愚弄.)

(If it was sufficient to know the answer to this question after invoking the method, then you could perhaps replace the empty method in the base class with a method that sets a private flag, which would indicate the method was not overridden. However this might be fooled if the derived class invokes base.PreValidate() in its overridden implementation.)

如果需要这种灵活性,也许最好的解决方案是使用完全不同的可扩展性机制?

Perhaps the best solution would be to use a completely different extensibility mechanism if this level of flexibility is required?

推荐答案

您可以使用接口来模拟它:

You can emulate this with interfaces:

public interface ISupportPreValidate
{
    void PreValidate();
}

public interface ISupportPostValidate
{  
    void PostValidate();
}

public class Base
{
    public void Validate()
    {
        if(this is ISupportPreValidate)
            ((ISupportPreValidate)this).PreValidate();

        // Validation logic

        if(this is ISupportPostValidate)
            ((ISupportPostValidate)this).PostValidate();            
    }
}

然后在 Base 派生的类中实现所需的接口.

And then implement required interfaces in Base-derived classes.

这篇关于是否可以判断派生类中是否已重写.NET虚拟方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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