简体   繁体   English

用Reflection覆盖私有方法

[英]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). 好吧,它需要是virtual才能覆盖它(通过编写从类继承的动态类型),并且你不能拥有private virtual (它没有意义)。 You could perhaps override an internal virtual , but I suspect even this may hit security issues. 您可以覆盖internal virtual ,但我怀疑这可能会遇到安全问题。 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. 也许您可以做的最好的事情是使用Reflection,结合Reflection.EmitCodeDom将类复制到新的命名空间中。 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. 注意:使用CodeDom,您必须在内存中构建图形,编译它,然后加载生成的程序集。

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. 另一种方法是使用Reflector来反汇编类,使用方法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. 你需要使用某种AOP。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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