简体   繁体   中英

Overriding a private method with Reflection

是否可以通过在.NET 3.5中使用Reflection来覆盖私有方法?

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.

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.

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

Typemock Isolator应该能够做到这一点,但是通过.NET Profiler API实现这一点(根据Roy Osherove的“单元测试艺术” )。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM