开发者

How to wrap a method via attributes?

开发者 https://www.devze.com 2022-12-19 01:14 出处:网络
I\'m wondering if it\'s possible to wrap a method only by adding an attribute. Example: I want to log the execution time a method takes.

I'm wondering if it's possible to wrap a method only by adding an attribute.

Example: I want to log the execution time a method takes.

[LogTimings]
public void work()
{
  ..
}
开发者_如何学编程

This is kind of wrapping a method into another one (see this python implementation).


AOP is possible in .NET. Here's an article about it. And here's a list of AOP frameworks for .NET.


Have a look at PostSharp, an AOP framework for .NET.

In terms of logging and timing, there's also a framework called Gibraltar which integrates with PostSharp and which should make it easier to collect and use the results. I keep meaning to get round to trying it...


Using only the standard .NET framework library, you would have to create the wrap functionality by deriving from System.Runtime.Remoting.Proxies.RealProxy.

This functionality you then can apply to your class, but this class has to derive from System.MarshalByRefObject.

This is quite some restriction, that's why you might want to look at 3rd party components like PostSharp.


You can do this without having to use a different compiler if you use PostSharp.


I wrote some stuff about AOP on .Net here: Help and Information about Aspect Oriented Programming

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号