使用反射覆盖私有方法
.NET 3.5 中是否可以使用 Reflection 重写私有方法?
Is it possible to override a private method by using Reflection in .NET 3.5?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
.NET 3.5 中是否可以使用 Reflection 重写私有方法?
Is it possible to override a private method by using Reflection in .NET 3.5?
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(4)
好吧,它需要是虚拟的才能覆盖它(通过编写从类继承的动态类型),并且您不能拥有私有虚拟(这没有意义)。您也许可以覆盖
内部虚拟
,但我怀疑即使这样也可能会遇到安全问题。所以最终我会说不。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.不能单独使用反射。也许您能做的最好的事情就是使用 Reflection 并结合 Reflection.Emit 或 CodeDom 将类复制到新的命名空间中。当您遇到要替换的私有方法时,您不会复制它,而是发出替换方法。
然而,开发人员可以使用许多技术,从而使这项技术变得非常非常困难。将类的实现分解为许多私有或内部类就是其中之一。
注意:使用 CodeDom,您必须在内存中构建图形,对其进行编译,然后加载生成的程序集。
这可能带来的麻烦比其价值要多得多。
另一种方法是使用 Reflector 来反汇编该类,编写代码并使用替换方法从中构建您自己的类。同样,还有重大的技术和法律障碍需要克服。不过,您可能会从反汇编代码中学到很多东西。
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.
不是通过使用反射。您需要使用某种 AOP。
Not by using Reflection. You need to use some sort of AOP.
Typemock Isolator 应该能够做到这一点,但通过 .NET 探查器 API 来实现(根据Roy Osherove 在单元测试的艺术中)。
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).