使用Delegate在方法入口和出口处执行代码
我的代码执行非常重复的操作,例如记录方法进入和退出。在这之间,我执行一些业务逻辑。有没有办法让我可以用代表来处理这个问题?
这是我到目前为止所拥有的。然而,由于我必须传递 func 参数,它确实受到限制。有人有更好的主意吗?
Func<Func<int>, int> logAction = new Func<Func<int>, int>(func =>
{
try
{
Console.WriteLine("Logging...");
return func();
}
finally
{
Console.WriteLine("End Logging...");
}
});
I have code that does very repetitive things such as logging the method entry and exit. In between, I execute some business logic. Is there a way I could handle that with a Delegate?
Here is what I have so far. However, it is really restrictive due to the func parameters I must passing. Anybody has a better idea?
Func<Func<int>, int> logAction = new Func<Func<int>, int>(func =>
{
try
{
Console.WriteLine("Logging...");
return func();
}
finally
{
Console.WriteLine("End Logging...");
}
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Postsharp 非常适合这一点 - 它是一个面向方面的编程库,具有编译时编织的功能,因此它不会像运行时编织那样影响性能。如果您是 AOP 新手,这可能无法解释太多,但基本上,它将允许您声明像这样的方法的日志记录:
有关使用 postsharp 进行日志记录的示例(和源代码),请参阅 http://www.sharpcrafters.com/solutions/logging
Postsharp is perfect for this- it is an Aspect Orientated Programming library that features compile time weaving, so it wont impact on performance like run time weaving. This probably doesn't explain much if your new to AOP but basically, it will allow you to declare logging on a method like this:
For an example (and source code) on using postsharp for logging, see http://www.sharpcrafters.com/solutions/logging
看来 AOP 框架之一可以解决你的问题。
It seems that one of the AOP frameworks could solve your issue.
无返回值的示例用法:
有返回值的示例用法:
Sample usage with no return value:
Sample usage with return value:
最简单的方法是将所有内容包装在 Action 中,然后在方法中执行它
然后调用它,为您的函数创建一个通用操作
The easiest way to do this is to wrap everything inside of an Action and then just execute that in a method
Then call it creating a generic action for your function