假设我想将一个函数包装在另一个函数中,以便向包装的函数添加一些功能。但我事先不知道返回类型或参数,因为这些方法是作为 Web 服务代理生成的。
我的第一个想法是使用 Func
。但某些函数可能会返回 void,在这种情况下 Action
会更合适。
现在我的问题是:是否有一个很好的通用方法来实现这一目标?我需要寻找一些模式吗?
Say I want to wrap a function in another function, so to add some functionality to the wrapped function. But I don't know the return type or parameters on beforehand as the methods are generated as a web service proxy.
My first train of thought was using Func<T>
. But some functions might return void, in which case Action<T>
would be more appropriate.
Now my question: is there a nice generic way to achieve this? Is there some pattern I need to look for?
发布评论
评论(2)
好吧,我想到了 外观模式...这不是一种非常自动的做事方式,但它有效。基本上,您只需将另一个接口放在代理前面并调用它即可。然后您可以添加任何您想要的功能。
解决此问题的另一种方法是使用面向方面的编程。我过去曾使用 PostSharp (当它免费时)来执行此操作。您可以通过向方法/属性添加属性来执行诸如在函数中添加预处理/后处理之类的操作。然后,AOP 组件使用代码编织来重写您的 IL,以包含您引用的代码。请注意,这会显着减慢构建过程。
Well, the Facade Pattern comes to mind... It's not a very automatic way of doing things, but it works. You basically just put another interface in front of the proxy and call that instead. You can then add any functionality that you desire.
Another way to approach this is with aspect oriented programming. I've used PostSharp (when it was free) to do this this in the past. You can do things like add Pre / Post processing in the function by adding an attribute to a method / property. The AOP components then use code weaving to rewrite your IL to include the code that you've referenced. Note that this can significantly slow the build process.
正如您所说“我事先不知道返回类型或参数”,我认为动态代理就是您想要的
需要。
不幸的是,我只知道Java中的动态代理。但我确信 C# 也有类似的东西。
尝试谷歌搜索“动态代理 C#”。
例如,这里似乎有 C# 的实现: http://www.castleproject.org/dynamicproxy/< /a>
那么,什么是动态代理?
来自 JavaDoc http://docs.oracle.com/javase/1.3/docs/guide/reflection/proxy.html#api:
As you say "I don't know the return type or parameters on beforehand", I think a Dynamic Proxy is what you
need.
Unfortunately, I know about the Dynamic Proxy in Java only. But I am sure, there is something similar for C#.
Try Googling "Dynamic Proxy C#".
For example, there seems to be an implementation for C# here: http://www.castleproject.org/dynamicproxy/
So, what IS a Dynamic Proxy?
From the JavaDoc http://docs.oracle.com/javase/1.3/docs/guide/reflection/proxy.html#api: