为什么Windsor只能拦截虚方法或接口方法?
我正在阅读文档,发现如果不使用接口,那么 Windsor 只能拦截虚拟方法?
这是 Windsor 的限制还是 C# 语言的限制?我正在寻找深入的答案。
I'm reading the documentation and see that if you don't use an interface then Windsor can only intercept virtual methods?
Is this a limitation with Windsor or simply the C# language? I'm looking for an in depth answer.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
C# 语言在这里完全无关。问题是拦截在运行时级别如何工作。
一种技术是从类继承/实现接口并将其用作代理。这显然只能重写虚方法和接口方法。我怀疑温莎使用了这种技术。这种技术的优点是它不需要任何特殊的东西。只需在运行时创建一个类即可。
另一种方法是使用分析 API。这允许您修改任何方法的 IL,包括非虚拟方法。这更具侵入性,通常仅在测试遗留代码时使用。
另一种方法是在构建时使用 IL 重写。这可以在您编写的代码中添加拦截点,但不能在框架代码中添加拦截点。
The C# language is completely irrelevant here. The question is how the interception works at the runtime level.
One technique is inheriting from the class/implementing the interface and using that as a proxy. This can obviously only override virtual methods and interface methods. I suspect Windsor uses this technique. The advantage of this technique is that it doesn't need anything special. Just create a class at runtime.
Another way is using the profiling API. This allows you to modify the IL of any method, including non virtual ones. This is much more intrusive, and typically only used when testing legacy code.
Yet another way is using IL rewriting at build time. This can add interception points in code you wrote, but not in framework code.
这是 .NET 框架的限制。 Windsor 产生一个动态实现,它要么实现一个接口,要么覆盖一个虚拟成员。 .NET 不允许覆盖非虚拟成员。
It's a limitation of the .NET framework. Windsor produces a dynamic implementation, which either implements an interface or overrides a virtual member. .NET does not allow members that are not virtual to be overridden.
既不是也不是。 Windsor 通过子类化工作,您只能明智地重写虚拟方法 - 或者可以实现接口。
其他任何事情都需要调试器/分析器挂钩处于活动状态,而这很难做到 - 一些模拟框架支持,ti,尽管它们都不是免费的。
Neither nor. Windsor works by subclassing and you can only override virtual methods sensibly - or interfaces can be implemented.
Anything else requires debugger/profiler hooks active and that is hard to do - some mocking frameworks support, ti, though none of them are free.
是的,你需要虚拟,但这只是因为微软搞砸了这种行为,例如,如果你看看 Java,默认情况下一个方法是开放扩展的,你必须明确地将其标记为密封。
阅读有关 SOLID 原则的更多信息,特别是开闭原则。
Yes you need virtuals but that is just because Microsoft has screwed up this behavior, if you look at Java for instance a method is open for extension by default, you have to explictly mark it as sealed.
Read more on SOLID principles, specificly Open Closed Principle.