Is it possible to override a private method by using Reflection in .NET 3.5?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Generic Generics in Managed C++
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
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.
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 aprivate virtual
(it makes no sense). You could perhaps override aninternal virtual
, but I suspect even this may hit security issues. So ultimately, I'd say no.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).