Overriding a private method with Reflection

2020-03-14 01:54发布

Is it possible to override a private method by using Reflection in .NET 3.5?

4条回答
走好不送
2楼-- · 2020-03-14 02:38

Not by using Reflection alone. Perhaps the best you could do is to use Reflection, combined with Reflection.Emit or the CodeDom to duplicate the class into a new namespace. When you come across the private method you want to replace, you don't copy it, you emit your replacement.

However, there are many techniques a developer can use that make this technique much, much harder. Breaking the implementation of the class into many private or internal classes is one such.

Note: using the CodeDom you'd have to build the graph in memory, compile it, and then load the resulting assembly.

This is probably a LOT more trouble than it is worth.

The other way to do it would be to use Reflector to disassemble the class, take the code and build your own class from it with the method replace. Again there are significant technical and legal hurdles to overcome. You may learn a lot from the disassembled code though.

查看更多
forever°为你锁心
3楼-- · 2020-03-14 02:42

Not by using Reflection. You need to use some sort of AOP.

查看更多
姐就是有狂的资本
4楼-- · 2020-03-14 02:45

Well, it would need to be virtual to be possible to override it (by writing a dynamic type that inherits from the class), and you can't have a private virtual (it makes no sense). You could perhaps override an internal virtual, but I suspect even this may hit security issues. So ultimately, I'd say no.

查看更多
Explosion°爆炸
5楼-- · 2020-03-14 02:53

Typemock Isolator is supposed to be able to do this, but does so through the .NET profiler APIs (according to Roy Osherove in The Art of Unit Testing).

查看更多
登录 后发表回答