问题
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.
回答1:
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.
回答2:
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.
回答3:
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.
回答4:
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.
来源:https://stackoverflow.com/questions/8576434/why-can-windsor-only-intercept-virtual-or-interfaced-methods