如何调用(非虚拟)的虚拟方法的最初的实现? [英] How to invoke (non virtually) the original implementation of a virtual method?

查看:97
本文介绍了如何调用(非虚拟)的虚拟方法的最初的实现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下情况:

在第三方库(不能修改):

In a 3rd party library (can not be modified):

class A { public virtual void M() {} }

class B : A { public override void M() {} }

在我自己的code:

class C : B { public override void M() {} }

C 的实现方法 M 我要打电话 A 的(但不是 B 的!)。可以吗?

From C's implementation of method M I want to call A's (but not B's!!). Can I?

接受任何技巧,反思包括在内。我想反射了,但使用的MethodInfo ,我从获得的typeof(A)仍然会产生一个虚拟呼叫(主叫 C 的实施与后续的堆栈溢出)。

Any tricks accepted, reflection included. I tried reflection already, but using the MethodInfo that I get from typeof(A) still generates a virtual call (calling C's implementation with subsequent stack overflow).

派生 C A 是出了问题,由于重新实现的复杂度

Deriving C from A is out of the question due to the complexity of reimplementing B.

推荐答案

您可以生成动态的方法来进行代理使用电话(不CallVirt)指令

you can generate dynamic method to make proxy that use Call (not CallVirt) instruction

        var x = new C();
        var m = typeof (A).GetMethod("M");
        var dm = new DynamicMethod("proxy",  typeof (void), new [] {typeof(C)}, typeof (C));
        var il = dm.GetILGenerator();
        il.Emit(OpCodes.Ldarg_0);
        il.Emit(OpCodes.Call, m);
        il.Emit(OpCodes.Ret);
        var action = (Action<C>)dm.CreateDelegate(typeof (Action<C>));
        action(x);

这篇关于如何调用(非虚拟)的虚拟方法的最初的实现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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