部队调用派生类以外的基方法 [英] Force calling the base method from outside a derived class

查看:144
本文介绍了部队调用派生类以外的基方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个类:

public class MyBase
{
    public virtual void DoMe()
    {

    }
}

public class MyDerived:MyBase
{
    public override void DoMe()
    {
        throw  new NotImplementedException();
    }
}

和我有以下代码来实例化MyDerived:

And I have the following code to instantiate MyDerived:

        MyDerived myDerived=new MyDerived();



的事情是如何调用基类的圆顶?如果使用myDerived.DoMe(),则派生方法时便会调用,产生一个例外。我试着投myDerived到MyBase,但它仍然是被调用的方法的衍生版本。

The thing is how to call DoMe of the base class? If I use myDerived.DoMe(), then the derived method wil be called, resulting in an exception. I tried to cast myDerived to MyBase, yet it is still the derived version of the method that gets called.

编辑:正如在下面的评论中提到,我不能改变eitehr MyDerived或MyBase,因为他们不是我的代码

As mentioned in the below comment, I can't change eitehr MyDerived or MyBase because they are not my code.

推荐答案

有一个解决方案,但它的丑陋:使用反射来获取基类的方法,然后放出必要IL调用它。请查看这个博客帖子它说明了如何做到这一点。我已经成功地使用这种方法它来调用基类的实现方法的时候我只有一个派生类,它会覆盖方法的引用。

There's a solution, but it's ugly: use reflection to get the base-class method, and then emit the IL necessary to call it. Check out this blog post which illustrates how to do this. I've successfully used this approach it to call the base class's implementation of a method when all I have is a reference to a derived class which overrides that method.

这篇关于部队调用派生类以外的基方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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